当设备进入睡眠模式时,服务无法正常工作

问题描述 投票:1回答:1

我创建了一个简单的Android应用程序,每分钟发送一次通知。为此我在这个应用程序中使用服务。查看下面的服务代码。

public class notiService extends Service {
    private final static int interval = 1000 * 60;
    Handler myHandler;
    Runnable myRunable;
    MediaPlayer mp;
    Intent intent;

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

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
        mp = MediaPlayer.create(this,R.raw.noti2);
        createRunnable();
        startHandler();
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        /**
         * Destroy Handler and Runnable
         */
        myHandler.removeCallbacks(myRunable);
        super.onDestroy ();
    }

    /**
     * Runnable method
     */
    public void createRunnable(){
        myRunable = new Runnable() {
            @Override
            public void run() {
                mp.start();
                send_notification("Notification title", "10");
                myHandler.postDelayed(this, interval); /* The interval time */
            }
        };
    }

    /**
     * Handler method
     */
    public void startHandler(){
        myHandler = new Handler();
        myHandler.postDelayed(myRunable, 0);
    }

    /**
     * Notification method
     */
    public void send_notification(String title, String min){
        intent = new Intent(getApplicationContext(),MainActivity.class);
        //intent.putExtra("open_fragment","open_f2");
        PendingIntent my_pIntent = PendingIntent.getActivities(notiService.this,0, new Intent[]{intent},0);
        Notification mynoti = new Notification.Builder(notiService.this)
                .setContentTitle(title)
                .setContentText("It will be start after "+min+" minutes.")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(my_pIntent).getNotification();
        mynoti.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(0,mynoti);
    }
}

它在应用程序运行时正常工作。但是,如果我关闭应用程序并且设备进入睡眠模式,则此代码无法正常工作。这次它在10分钟或更长时间后发送通知。

我无法理解为什么它会像这样!我怎么能解决这个问题?感谢您的答复。

java android service
1个回答
0
投票

你正在使用处理程序。当设备进入睡眠状态时,处理程序不起作用。你可以看到这个link在睡眠模式下运行处理程序

© www.soinside.com 2019 - 2024. All rights reserved.