Blog of CodeJELLOW’S ENGINEERING NOTES
← 返回文章

Android JetPack学习总结(二十)

Android JetPack学习总结(二十) Service(一)

本文目录 ⌄
  1. Service(一)

Service(一)

创建一个Service如同创建其它三大组件一样,需要在Manifests中声明之。

启动服务:

TEXT
@Overrideprotected void onStart() {    super.onStart();    Log.i(TAG, "onStart: activity");    Intent intent=new Intent(this,MyService.class);    this.startService(intent);}

关停服务:

TEXT
@Overrideprotected void onStop() {    super.onStop();    Log.i(TAG, "onStop: activity");    Intent intent=new Intent(this,MyService.class);    this.stopService(intent);}

在Service内部关停服务:

TEXT
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    Log.i("hello","onStartCommand: Service");    stopSelf();    return super.onStartCommand(intent, flags, startId);}
使用具有生命周期的LifeCycleService:

添加依赖

TEXT
implementation "android.arch.lifecycle:extensions:1.1.1"

java不支持协程。

绑定服务

在Service中增加继承Binder的子类,并重写OnBind方法:

TEXT
public class MyService extends LifecycleService {
    private MutableLiveData<Integer> number=new MutableLiveData<>();
    public MyService() {
        number.setValue(0);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        super.onBind(intent);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    number.postValue(number.getValue()+1);
                }
            }
        }).start();
        return new MyBinder();
    }

    public class MyBinder extends Binder{
        MyService service=MyService.this;
    }

    public MutableLiveData<Integer> getNumber() {
        return number;
    }
}

在Activity中启动绑定:

TEXT
buttonBind.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View view) {        Log.i(TAG,"onclick");        Intent bindIntent=new Intent(MainActivity.this,MyService.class);        ServiceConnection connection=new ServiceConnection() {            @Override            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {                ((MyService.MyBinder)iBinder).service.getNumber().observe(MainActivity.this, new Observer<Integer>() {                    @Override                    public void onChanged(Integer integer) {                        textView.setText(integer.toString());                    }                });            }            @Override            public void onServiceDisconnected(ComponentName componentName) {            }        };        bindService(bindIntent,connection,BIND_AUTO_CREATE);    }});
通过 RSS 订阅更新 →