Android service 精辟解说


本地服务

所谓本地服务,其实就是完全服务于一个进程的组件。本地服务的这种特性决定了它有特别的启动方式。通常这类服务的典型案例,就是邮件轮询。

调用Context.startService()启动服务

package net.bpsky;   import Android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder;   public class DoudingService extends Service {           private NotificationManager notificationMgr;       @Override     public IBinder onBind(Intent arg0) {         // TODO Auto-generated method stub         return null;     }           @Override     public void onCreate(){         super.onCreate();                   notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);         displayNotificationMessage("Starting Background Service!");         Thread thr = new Thread(null,new ServiceWorker(),"BackgroundService");         thr.start();     }           class ServiceWorker implements Runnable{         public void run(){             // bla bla bla...         }     }           @Override     public void onDestroy(){         displayNotificationMessage("Stopping Background Service");         super.onDestroy();     }           @Override     public void  onStart(Intent intent,int startId){         super.onStart(intent, startId);     }           private void displayNotificationMessage(String message){         Notification notification = new Notification(R.drawable.note,message,System.currentTimeMillis());         PendingIntent contentIntent = PendingIntent.getActivity(this,0,new Intent(this,FeedActivity.class),0);         notification.setLatestEventInfo(this, "background Service", message, contentIntent);         notificationMgr.notify(R.id.app_notification_id,notification);     }   }

远程服务

支持onBind()方法的,就是远程服务。远程服务并不是说一定要远程访问,而是支持(RPC,Remote Procedure Call,远程过程调用)。这类服务的典型案例就是应用程序之间执行通信。比如:路由服务,将信息转发至其它应用程序。远程服务最重要的一个特性就是需要AIDL(Android Interface Definition Language)向客户端定义自身。

  • 定义AIDL接口
  • 调用Context.bindService()绑定调用
  • 优势在于允许不同进程进行绑定调用
  • 在使用bindService时是异步操作,目标服务如果未在后台运行,那么在链接过程中会被启动。

下面我们来作一个调用模拟,可以看到图例大概的结构是这样的。

服务端(RPCService)

  • 1
  • 2
  • 3
  • 4
  • 下一页

相关内容