作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 android 应用程序中运行后台服务。我已经尝试了标准的方法和很多其他的调整。问题是,当应用程序从最近的应用程序中关闭时,该服务会被终止。这只发生在像 Oppo、Vivo、Xiomi 等中国 Android 设备上。它在所有其他品牌上都能正常工作。
我尝试了以下解决方案。
OnStartCommand()
Activity 返回START_STICKY
.在应用程序按预期关闭后,这仍然不会重新启动 Activity 。@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
DOZE
中不会关闭它来省电模式。 Auto-Start
从手机的安全设置。 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
onTaskRemoved()
中被杀死后实现了启动服务的警报管理器方法和 onDestroy()
服务的方法。<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false" />
@Override
public void onTaskRemoved(Intent rootIntent){
Log.d("Service:","I am being closed!");
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
/>
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops!");
context.startService(new Intent(context, MyService.class));;
}
}
最佳答案
这主要是为了优化电池和提高手机性能,
正如你已经尝试过我的 solution但您仍然在某些设备中遇到此问题,
所以这是从最近的应用程序列表中滑动杀死应用程序的替代解决方案,
关于android - 中国安卓设备杀后台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61027722/
我是一名优秀的程序员,十分优秀!