- Service 与 Activity 通信
class DemoService extends Service{
private DemoBinder mDemoBinder=new DemoBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mDemoBinder;
}
class DemoBinder extends Binder{
// public void doAnything(){}
}
}
private DemoService.DemoBinder mBinder;
private ServiceConnection mServiceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// mBinder=(DemoService.DemoBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
2.Service 的生命周期
// Service 只有一个实例
// onCreate只会执行一次
startService()-->onCreate()-->onStartCommand()-->stopService()/stopSelf()-->onDestroy()
bindService()-->onCreate()-->onBind()-->unbindService()-->onDestroy()
3.Service 防止被回收: 前台服务
class DemoService extends Service{
@Override
public void onCreate() {
Intent i=new Intent(this,MainActivity.class);
PendingIntent pi=PendingIntent.getActivities(this,0,i,0);
Notification notification=new NotificationCompat.Builder(this)
.setContentTitle("This is my Demo Foreground service")
.setContentText("xx")
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.build();
// startForeground(1,notification);
}
4.IntentService
class DemoIntent extends IntentService{
// 必须构造无参数构造调用父类有参构造函数
public DemoIntent() {
super("DemoIntent");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}