高级进阶必会之服务

Service小结

  • 按种类
    Local
    Remote
  • 类型
    前台(Notification)
    后台
  • 启动方式
    Start
    bind
  • Service与Thread与Process
  • Service的生命周期
    onCreate
    onStart
    onBind
    onDestory等

AndroidMainfest.xml中的Service

  • android:name
  • android:label
  • android:icon
  • android:permission
  • android:process
  • android:enabled
  • android:exported

Service的一些补充知识点

  • Service>

  • 远程服务
    Messenger
    public class MessengerActivity extends Activity {
    private Messenger mMessenger;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
    // 当与service的连接建立后被调用
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    mMessenger = new Messenger(service);
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bindService(new Intent(this, MessengerService.class),mServiceConnection, Context.BIND_AUTO_CREATE);
    if(mMessenger != null){
    Message message = Message.obtain(null, 0, "hello");//发送Message
    try {
    mMessenger.send(message);
    } catch (RemoteException e) {
    e.printStackTrace();
    }
    }
    }}
    服务端(接收Message)

      public class MessengerService extends Service { 
         // 适合于多进程,单线程。。不需要考虑线程安全
          Messenger mMessenger = new Messenger(new IncomingHandler());
          class IncomingHandler extends Handler{
              @Override
              public void handleMessage(Message msg) { 
                 super.handleMessage(msg);             // 处理消息
                  switch (msg.what){
                      case 0:                    
      // fdsfdskfdlsj;
                          break;
                  } 
             } 
         }
          @Nullable
          @Override
          public IBinder onBind(Intent intent) {
              return mMessenger.getBinder();
          }}

你可能感兴趣的:(高级进阶必会之服务)