[英]Service doesn't work properly when device go to sleep mode
我創建了一個簡單的android應用,該應用每分鍾都會發送一次通知。 為此,我在此應用程序中使用Service 。 看下面的服務代碼 。
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分鍾或更長時間后發送通知。
我不明白為什么會這樣! 我該如何解決這個問題? 感謝您的答復。
您正在為此使用處理程序。 設備進入睡眠狀態時,處理程序不起作用。 您可以看到此鏈接以在睡眠模式下運行處理程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.