android - 无论我做什么,服务都会睡觉
问题描述
这是我目前的精简服务,它并不漂亮,但它可以完成这项工作,主要是:
public class TimerService extends Service {
public static volatile boolean execute = true;
public TimerService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
new Thread(new Runnable(){
public void run() {
int type = sharedPreferences.getInt(getString(R.string.type), 1);
int time = sharedPreferences.getInt(getString(R.string.duration) + ".min", 0) / 2;;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
Intent DeleteIntent = new Intent(getApplicationContext(), DeleteNotification.class);
DeleteIntent.putExtra("ID", 123);
DeleteIntent.putExtra("Service", true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),1, DeleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
while (time > 0 && execute) {
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_stat_watch_later)
.setContentTitle("title")
.setContentText("time: " + time)
.addAction(R.drawable.ic_info_black_24dp, "cancel", pendingIntent)
.setPriority(Notification.PRIORITY_MAX)
.setOngoing(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
startForeground(123, notification);
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
time--;
}
execute = true;
stopSelf();
}
}).start();
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
问题是我需要这项服务继续运行 5-50 分钟。如果手机屏幕打开,它工作正常,但如果它关闭它,服务就会进入睡眠状态。我尝试使用 WakeLock (实际上由于某种原因冻结了服务,即使我基本上粘贴了它)和使用 startForeground 保持服务活动,但服务仍然停止。这针对 API 21+。我对该怎么做没有想法。它根本不想保持活跃。
解决方案
推荐阅读
- java - ScheduledExecutorService 在给定时间段内以给定时间速率执行任务
- c# - Unity 无标记地理定位 AR
- r - 时间累计
- python-3.x - Python multiproccesing.Procces 不并行运行
- javascript - 在数组的开头放置一个空值
- spring-boot - Gradle bootRun 失败?
- bash - bash:无法执行二进制文件 exec 格式错误 fortran
- android - 每当我尝试添加新的字符串资源时,Strings.xml 都会出现翻译错误
- php - Laravel 默认验证错误消息不起作用
- php - PHP 文件格式问题:如何解决写入输出中的不一致问题?