我试图在关闭应用程序后在后台向服务器发送http请求。但是线程总是被杀死。我已经尝试过Workmanager,AlarmManager和BackgroundService。在过去的几周里,我一直在互联网上寻找解决方案,但是找不到在较新的API上运行且没有ForegroundService且在运行时必须显示通知的解决方案。
启动AlarmManager:
//NotificationAlarm is the class implementing BroadcastReceiver
Intent intent = new Intent(context, NotificationAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), 10000, pendingIntent);
直到Android 6,AlarmManager才对我起作用。但是在最新版本中,它一直处于关闭状态。
我使用以下教程作为BackgroundServices的模板,但仍然无法正常工作:https://medium.com/@raziaranisandhu/create-services-never-stop-in-android-b5dcfc5fb4b2
我期待一个答案。
答案 0 :(得分:0)
您曾经尝试过ForegroundService吗?... 您可以创建扩展为服务btw的类,只需在清单上添加意图过滤器即可。 朋友班上的例子。
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
}
@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_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
并以
startForegroundService(context,ForegroundService.class);
有很多选择 (前台服务将启动通知,直到通知消失)