Gio*_*gen 5 java multithreading android
由于Android O不允许在不通知用户的情况下启动后台服务,因此我想选择使用Firebase Jobdispatcher在后台运行新线程的不同方法,请参阅:https://github.com/firebase/firebase -jobdispatcher,机器人
在构建API 26之前,我曾经在服务中启动一个新线程.这是一个STICKY服务,并将在用户从最近关闭应用程序时重新启动(当幻灯片从正在运行的应用程序中删除应用程序时).
在下面的API 26之前查看我的原始代码.
public class NotificationService extends Service {
@Override
public void onCreate() {
// this will start the thread
ApplicationLoader.postInitApplication();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
Run Code Online (Sandbox Code Playgroud)
在API 26中,出现了一些限制:
https://developer.android.com/about/versions/oreo/android-8.0-changes.html#back-all
所以上面的方法不再起作用了.但即使用户从最近的应用程序关闭应用程序,我仍然希望我的线程能够运行.我发现了一种解决方法,但对我来说感觉非常糟糕.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher
(new GooglePlayDriver(applicationContext));
Job notificationJob = dispatcher.newJobBuilder()
.setService(NotificationService.class)
.setTag("backgroundJob-" + System.currentTimeMillis())
.setRecurring(true)
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
.setTrigger(Trigger.executionWindow(50, 60))
.setReplaceCurrent(false)
.build();
dispatcher.mustSchedule(notificationJob);
Run Code Online (Sandbox Code Playgroud)
服务:
public class NotificationService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
// this will check if the thread is started, if not it will start the thread
ApplicationLoader.initNotificationThread();
return false;
}
@Override
public boolean onStopJob(JobParameters job) {
return false;
}
Run Code Online (Sandbox Code Playgroud)
现在我找到了一个解决方法,如果我的线程已经运行,这个作业每50/60秒检查一次,如果没有,它将启动一个线程.即使用户从最近的应用程序中删除应用程序,这仍然有效.
但是,这种解决方案感觉不舒服.我每分钟安排一次密集检查,而这甚至可能没必要.
有没有更好的方法来解决这个问题?我可以做一些电话,比如在onDestroy()某个地方打电话然后开始新工作吗?
| 归档时间: |
|
| 查看次数: |
661 次 |
| 最近记录: |