Android编写绑定Service方法

  • 绑定Service对应的Activity可以调用Service里面的方法。说白了就是可以拿到Service的对象

  • Activity销毁对应的Service也就没了

  • Service写法

public class MyService extends Service{

    private final static String TAG = "wzj";
    private int count;
    private boolean quit;
    private Thread thread;
    private LocalBinder binder = new LocalBinder();

    public class LocalBinder extends Binder{
        MyService getService(){
            return MyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程中执行
                //每间隔一秒count加1;知道quit 为true
                while (!quit){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        });
        thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        this.quit = true;
        super.onDestroy();
    }

    public int getCount(){
        return count;
    }

    public boolean onUnBind(Intent intent){
        return super.onUnbind(intent);
    }
}
  • 清单文件中配置方法

  • 对应的Activity中有个成员变量
private MyService mService;
  • 对应获取Service方法
ServiceConnection conn = new ServiceConnection() {
//与服务交互的接口方法,绑定服务的时候被回调,在这个方法获取绑定Service传递过来的Ibinder对象
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        //获取Binder
        MyService.LocalBinder binder = (MyService.LocalBinder) iBinder;
        mService = binder.getService();
    }

    //取消绑定回调,一般不调用
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mService = null;
    }
}
  • 启动方法
Intent intent = new Intent(this,MyService.class);
bindService(intent,conn, Service.BIND_AUTO_CREATE);
  • 这样就可以使用获取到的mService调用其中的方法

你可能感兴趣的:(Android基础)