无论我做什么,服务都会进入睡眠状态

时间:2018-05-01 18:39:22

标签: 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+的。我没想到该做什么。它根本不想保持活跃。

0 个答案:

没有答案