service保活
问题:
后台Service启动正常启动后,锁屏状态下大概80秒左右Service就被暂停了(并没有被杀死),唤醒屏幕后就继续执行。
解决思路:
Service启动时创建一条通知,与其绑定,这样锁屏或者后台Service都不会被暂停或杀死。
代码如下:
在Service的onCreate中创建NotificationChannel 并且与服务绑定。
@Override
public void onCreate() {
super.onCreate();
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.notify)
.setContentTitle("title")
.setContentText("text");
//创建NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String notificationId = "TgStartServiceId";
String notificationName = "TgStartServiceName";
NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
builder.setChannelId(notificationId);
}
Notification notification = builder.build();
startForeground(1, notification);
}
开启service:
需要根据版本判断是调用startForegroundService()或者startService()函数;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//android8.0以上通过s