它超过3周尝试了所有类型的后台服务,(intentservice ...等)它都可以工作,但是问题是在android进入睡眠模式后它停止了,所以为避免我尝试增加使用(runnble,thread和循环),但同样的问题,当暴民进入睡眠模式时,即使使用唤醒方法/权限,所有任务也会停止。
MainActivity(公共无效)[我用来执行任务]
public void do_my_task_every_25sec(){
// working for 1000 as total number.
for (int i = 0; i < 1000; i++) {
System.out.println("Starting Again Number :"+i);
Updating_Last_one = Long.parseLong(Updated.getText().toString());
.....
SystemClock.sleep(25000); // sleep 25 sec to start again.
}
}
目前没有提供服务的背景,我之前尝试过很多服务。
我将很高兴为您提供帮助,尽管我仍是Android开发中的新手,只是想确保即使在睡眠模式下任务也能正常工作,即使我关闭应用程序,服务也会停止。我相信Stackoverflow开发人员的力量,谢谢。
您应尝试使用前台服务。这将要求您在用户的通知栏上不断收到通知,但这将使您的进程继续运行。
只需确保您不耗尽他的电池。
这里是一个例子
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;
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}