Android 中国安卓设备杀死后台服务
我正在尝试在android应用程序中运行后台服务。我已经尝试了标准的方法和很多其他的调整。问题是,当应用程序从最近的应用程序关闭时,服务将被终止。这只发生在中国的安卓设备上,如Oppo、维梧、Xiomi等。它在所有其他品牌上都能正常工作 我尝试了以下解决方案Android 中国安卓设备杀死后台服务,android,android-studio,service,operating-system,oppo,Android,Android Studio,Service,Operating System,Oppo,我正在尝试在android应用程序中运行后台服务。我已经尝试了标准的方法和很多其他的调整。问题是,当应用程序从最近的应用程序关闭时,服务将被终止。这只发生在中国的安卓设备上,如Oppo、维梧、Xiomi等。它在所有其他品牌上都能正常工作 我尝试了以下解决方案 越过活动的OnStartCommand()返回START\u STICKY。在应用程序按预期关闭后,此操作仍不会重新启动活动 @Override public int onStartCommand(Intent intent, in
OnStartCommand()
返回START\u STICKY
。在应用程序按预期关闭后,此操作仍不会重新启动活动
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
DOZE
模式下关闭该应用程序以节省电池自动启动
的权限@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" />
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
/>
我已经尝试了在提供的解决方案,如上所述。这并不能解决我的问题。这些品牌有一个可以正常生存的应用程序白名单。如果您的应用程序不在白名单中,操作系统将强制停止在最近屏幕上刷过的任何应用程序。您必须告诉用户手动将您的应用添加到白名单 这主要是为了优化电池和提高手机性能 您已经尝试了我的,但仍然在某些设备中遇到此问题, 所以这里有一个替代的解决方案,可以从最近的应用列表中删除正在刷卡的应用
这回答了你的问题吗?不,我已经试过了。还是同样的问题。白名单包括自动启动许可、电池优化豁免和优先级认证许可。尝试了所有这些。如何以编程方式将应用添加到白名单?@frozenade无法以编程方式添加。您必须逐个联系设备供应商,以说服他们将您的应用程序添加到他们的白名单中。但他们99%不会接受这一点。您可以使用此库要求用户将您的应用程序添加到其设备的白名单中:这真是太棒了。从最近的工作中排除了它的魅力。谢谢大家!
android:excludeFromRecents=“true”
在空闲几分钟后工作。但在长时间闲置后,它无法再接收通知。请帮忙@frozenade你试过这个方法吗
<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));;
}
}