2012-12-15 67 views
0

我有一個在Android設備啓動後運行的服務。這每天執行兩個通知。但我有一個問題:它看起來像服務崩潰或自動重新啓動。此外,通知不會在指定的時間執行。我怎樣才能解決這個問題?有時我會看到敬酒Service CreatedService Started。謝謝!服務崩潰(或自動重新啓動)

代碼:

public class UnUsedService extends Service { 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show(); 
    } 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
    } 

    private PendingIntent pendingIntent; 

    @SuppressWarnings("deprecation") 
    @Override 
    public void onStart(Intent intent, int startId) { 

     super.onStart(intent, startId); 

     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 

     Calendar cal1 = Calendar.getInstance(); 
     cal1.set(Calendar.HOUR_OF_DAY, 05); //midday 
     cal1.set(Calendar.MINUTE, 45); 
     cal1.set(Calendar.SECOND, 00); 

     Calendar cal2 = Calendar.getInstance(); 
     cal2.set(Calendar.HOUR_OF_DAY, 17);//8pm for example 
     cal2.set(Calendar.MINUTE, 30); 
     cal2.set(Calendar.SECOND, 00); 

     AlarmManager am = (AlarmManager)getApplicationContext().getSystemService (Context.ALARM_SERVICE); 
     Intent intent2 = new Intent(getApplicationContext(), AlarmReceiver.class); 
     PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT); 
     am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi); 
    } 
}; 

回答

1

如果您的通知需要在特定時間運行,您應該使用AlarmManager安排他們。這會被Android保留下來,以便您的服務可以自由被殺死,並且必要時警報將會重新啓動。

這聽起來像你現在讓你的服務24/7全天候運行,以便它可以每天做兩件事;這是一個糟糕的Android公民!改爲使用AlarmManager將解決您的問題,並且可以讓您停止浪費資源。

+0

mhmh..my服務在我的應用外運行。當用戶重新啓動自己的設備時,無法打開應用程序。如果用戶沒有打開應用程序如何運行通知?我需要一項服務。或者弄錯了什麼?謝謝。 –

+0

如果您的服務正在啓動(通過BOOT_COMPLETED或其他方式),該服務可以安裝AlarmManager。 – mah

+0

我的服務以BOOT_COMPLETED開頭。如何通過服務「安裝」警報管理器?我的代碼不一樣嗎?謝謝。 –

相關問題