android 8.0可以实现后台包活么,自己用到的Android 双服务保活(适配8.0) | 韩小呆...

/**

* content:后台运行的服务

* Actor:韩小呆

* Time:2018/5/3

*/

public class RemoteService extends Service {

MyConn conn;

MyBinder binder;

@Override

public IBinder onBind(Intent intent) {

return binder;

}

@Override

public void onCreate() {

super.onCreate();

conn = new MyConn();

binder = new MyBinder();

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

this.bindService(new Intent(this, MainService.class), conn, Context.BIND_IMPORTANT);

return START_STICKY;

}

class MyBinder extends IMyAidlInterface.Stub {

@Override

public String getServiceName() throws RemoteException {

return RemoteService.class.getSimpleName();

}

}

class MyConn implements ServiceConnection {

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

}

@Override

public void onServiceDisconnected(ComponentName name) {

Intent intent = new Intent(RemoteService.this, MainService.class);

//开启本地服务

if (Build.VERSION.SDK_INT >= 26) {

\\适配8.0机制

RemoteService.this.startForegroundService(intent);

} else {

RemoteService.this.startService(intent);

}

//绑定本地服务

RemoteService.this.bindService(new Intent(RemoteService.this, MainService.class), conn, Context.BIND_IMPORTANT);

}

}

@Override

public void onDestroy() {

super.onDestroy();

Intent intent = new Intent(RemoteService.this, MainService.class);

//开启本地服务

if (Build.VERSION.SDK_INT >= 26) {

\\适配8.0机制

RemoteService.this.startForegroundService(intent);

} else {

RemoteService.this.startService(intent);

}

//绑定本地服务

RemoteService.this.bindService(new Intent(RemoteService.this, MainService.class), conn, Context.BIND_IMPORTANT);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值