Android

Android JetPack学习总结(二十)

Service(一)

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

启动服务:

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

关停服务:

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

在Service内部关停服务:

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

添加依赖

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

java不支持协程。

绑定服务

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

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中启动绑定:

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);
}
});

发表评论