我创建了一个简单的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分钟或更长时间后发送通知。
我无法理解为什么它会像这样!我怎么能解决这个问题? 感谢您的回复。