Android四大组件之服务

创建一个服务,并与活动绑定

作为安卓四大组件之一的服务,毫无例外也要在manifast中进行注册

  • 新建服务类继承于Service,并覆盖onBind( )方法,用于与活动绑定
public class MySevice extends Service {

    //创建DownloadBinder对象mBinder
    private DownloadBinder mBinder = new DownloadBinder();

    //创建DownloadBinder类,实现服务中需要等待活动指示来执行的方法
    class DownloadBinder extends Binder {
  //必须是pubilc修饰的方法
public int getProcess() { return 0; } } @Nullable @Override //返回DownloadBinder对象mBinder public IBinder onBind(Intent intent) { return mBinder; } @Override //创建服务时执行 public void onCreate() { Toast.makeText(this, "服务创建成功", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override //启动服务时执行 public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "服务启动成功", Toast.LENGTH_LONG).show(); return super.onStartCommand(intent, flags, startId); } @Override //关闭服务时执行 public void onDestroy() { Toast.makeText(this, "服务关闭成功", Toast.LENGTH_LONG).show(); super.onDestroy(); } }
  • 在Activity中找到传递过来的mBinder对象
    private MySevice.DownloadBinder mDownloadBinder;
    //创建匿名内部类ServiceConnection(),重写方法onServiceConnected(),onServiceDisconnected()分别在绑定和取消绑定时调用
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //向下转型,找到mDownloadBinder对象,并调用对象中的public方法
            mDownloadBinder = (MySevice.DownloadBinder) service;
            mDownloadBinder.getProcess();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
  • 绑定服务与活动
    Intent thread_bind_service = new Intent(ThreadDemoActivity.this, MySevice.class);
    bindService(thread_bind_service,mConnection,BIND_AUTO_CREATE);
    /* bindService()方法接收三个参数,第一个参数就是刚刚构建出的 Intent 对象,
    *  第二个参数是前面创建出的 ServiceConnection 的实例,
    *  第三个参数则是一个标志位,这里传入 BIND_AUTO_CREATE 表示在活动和服务进行绑定后自动创建服务
    */
  •  解除绑定
  unbindService(mConnection);

 

posted @ 2017-02-14 20:34  岑忠满  阅读(260)  评论(0编辑  收藏  举报