首页 > 解决方案 > 无论我做什么,服务都会睡觉

问题描述

这是我目前的精简服务,它并不漂亮,但它可以完成这项工作,主要是:

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+。我对该怎么做没有想法。它根本不想保持活跃。

标签: android

解决方案


推荐阅读