0

我的 Android 服务必须不断检查当前时间是否与保存的时间匹配。我使用了一个服务,它有一个计时器,每分钟检查当前时间是否与保存的时间匹配。如果 Android 进入睡眠模式,他会停止检查。我尝试了 WakeLocker 来解决这个问题。它有效,但它耗尽了我的电池。

我目前使用的代码如下。

    public class AlarmService extends Service {

    private static Timer timer = new Timer(); 
    private Context ctx;
    private WakeLock wakeLock;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
      return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
        super.onCreate();
        ctx = this; 
        startService();

        /* Wake locker
        PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
        wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Wake locker");
        wakeLock.acquire();
        */

    }

    private void startService()
    {           
        timer.scheduleAtFixedRate(new mainTask(), 0, 60000);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
        startService();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

    private class mainTask extends TimerTask
    { 
        public void run() 
        {
            toastHandler.sendEmptyMessage(0);
        }
    }  

    private final Handler toastHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Amsterdam"));
            Date currentLocalTime = cal.getTime();
            DateFormat date = new SimpleDateFormat("HH:mm", new Locale("nl", "nl"));
            date.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam")); 
                String currenttime = date.format(currentLocalTime); 

                DateFormat date2 = new SimpleDateFormat("EEEE", new Locale("nl", "nl"));
                date2.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam")); 
                    String currentday = date2.format(currentLocalTime); 

            if(currentday.equals("maandag")) { // "maandag" is dutch for Monday
                String tijd1 = "16:00";

                if(currenttime.equals(tijd1)) {
                    NotificationCompat.Builder mBuilder = 
                            new NotificationCompat.Builder(AlarmService.this)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentTitle("Test message") .setAutoCancel(true)
                            .setAutoCancel(true)
                            .setContentText("This is a test message");
                    Intent resultIntent = new Intent(AlarmService.this, MainActivity.class);
                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(AlarmService.this);
                    stackBuilder.addParentStack(MainActivity.class);
                    stackBuilder.addNextIntent(resultIntent);
                    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);
                    NotificationManager mNotificationManager = (NotificationManager) AlarmService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(1, mBuilder.build());

                }                
            }
        }
    }; 
}

有人有解决这个问题的方法,不会耗尽我的电池吗?所以它必须检查当前时间是否与保存的时间匹配,即使在 Android 处于睡眠状态时也是如此。

谢谢!

4

1 回答 1

2

使用 AlarmManager 安排代码块在您需要时运行。

您需要一个 AlarmManager 和一个扩展 BroadcastReceiver 的类。然后覆盖 onReceive() 方法并在其中放入您要运行的代码。设备只会在接收器内部的 onReceive() 方法持续时间内唤醒。

AlarmManager alarmManager = context.getSystemService(Context.ALARM_SERVICE) //Please note that context is "this" if you are inside an Activity

Intent intent = new Intent(context, MyReceiver.class);
PendingIntent event = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, millisToFireEvent, event);
于 2013-09-16T16:19:21.777 回答