我想在android Oreo版本中每30分钟跟踪一次用户。当用户从最近的应用托盘中删除时,跟踪服务将停止。我尝试使用前台服务/工作管理器,它在Pie中运行良好,但同样不适用于Oreo。
Intent serviceIntent = new Intent(this,ExampleService.class); serviceIntent.putExtra(“inputExtra”,input); ContextCompat.startForegroundService(此,serviceIntent);
example service.Java
public class ExampleService extends Service {
private Timer mTimer;
private Handler mHandler = new Handler();
private static final int TIMER_INTERVAL = 120000; // 2 Minute
private static final int TIMER_DELAY = 0;
@Override
public void onCreate() {
super.onCreate();
if (mTimer != null)
mTimer = null;
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new DisplayToastTimerTask(), TIMER_DELAY, TIMER_INTERVAL);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input=intent.getStringExtra("inputExtra");
Intent notificationIntent=new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,
notificationIntent,0);
Notification notification=new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_STICKY;
}
@Override
public void onDestroy() {
startAgainService();
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
startAgainService();
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class DisplayToastTimerTask extends TimerTask {
Handler mHandler = new Handler();
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Hello world every 5 minute", Toast.LENGTH_SHORT).show();
}
});
}
}
private void startAgainService() {
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);
}
}
一些设备制造商决定修改Android股票,以便在用户从最近的应用程序中刷出应用程序时强制停止该应用程序。
据WorkManager的公共发布者报道 - are the Chinese manufacturers (Huawei, Oppo, Xiaomi...) supported?,没有办法解决这个问题。
在这些情况下,您的工作将停止,直到用户再次启动您的应用。