android - 即使手机空闲,如何运行服务?
问题描述
我知道这个问题已经被问过很多次了。从其他 SO 问题来看,这就是我尝试过的。我每 15 分钟将设备位置和电话状态返回到 SQLITE,并在第二天将其发送到服务器。手机空闲时如何避免服务被Android杀死?(转换为系统应用程序是不可能的。)
@Override
public void onCreate() {
Log.e("onCreate", "Service Method");
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTimer != null) {// Cancel if already existed
mTimer.cancel();
mTimer = null;
}
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new ConnectActivity(), 0, 900000); //Schedule task
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
startServiceForeground(intent, flags, startId);
return Service.START_STICKY;
}
public int startServiceForeground(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, DeviceStatusService.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle("NOTIFICATION NAME")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.default)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(300, notification);
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent intent=new Intent(this,this.getClass());
startService(intent);
}
@Override
public void onDestroy() {
Log.e("onDestroy", "Service Method");
mTimer.cancel(); //For Cancel Timer
mTimer.purge();
mTimer = null;
super.onDestroy();
Intent broadcastIntent = new Intent("RestartService");
sendBroadcast(broadcastIntent);
}
另外,我用过这个manifest.xml
:
<receiver
android:name=".ServiceRestarterBroadcastReceiver"
android:enabled="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="RestartService" />
</intent-filter>
</receiver>
<service
android:name=".DeviceStatusService"
android:enabled="true"
android:stopWithTask="false"/>
ServiceRestarterBroadcastReceiver.class
public class ServiceRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
/*context.startService(new Intent(context.getApplicationContext(), DeviceStatusService.class));*/
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, DeviceStatusService.class));
} else {
context.startService(new Intent(context.getApplicationContext(), DeviceStatusService.class));
}
}
}, 60000);
}
}
我面临的问题是,如果屏幕关闭并且设备进入空闲状态,服务要么被杀死,要么不向数据库返回任何值。
PS:在使用设备时它工作正常。特别是当您不使用该设备时,此问题仍然存在。
解决方案
我认为,您不应该为此目的使用服务。您应该使用某种任务调度程序。它们有很多——AlertManager、JobSheduler 等。有时选择一个真的很棘手。我建议从这篇文章开始:https ://medium.com/mindorks/android-scheduling-background-services-a-developers-nightmare-c573807c2705
推荐阅读
- scala - 无法重写递归调用:它不在尾部位置
- django - 部署到 Google App Engine / Cloud SDK 的 Django 应用上的静态文件位置
- windows - 限制从 net start 命令运行的 Windows 服务使用的 CPU 内核数
- javascript - 如果数组中的列与 javascript 中存在的完全相等,则求和列
- sql - SQL 中的日期过滤
- c# - 类别分组
- java - 不断得到 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
- google-cloud-platform - 使用云函数与云作为对话流的 webhook 运行
- python - 装饰函数执行后从装饰器访问变量值
- python - 使用索引号删除 pandas 中的特定行