2013-12-11 89 views
2

我希望我的應用程序每天早上6點以「Good Morning」消息顯示通知。正如我讀到的,爲此我需要應用程序在後臺運行,所以我需要使用服務。服務在指定的時間每天創建一個通知

我試過下面的代碼,但我卡住了。

MainActivity.java

public void onClickStartService(View v) 
    { 
     startService(new Intent(this,MyService.class)); 
    } 

    public void onClickStopService(View v) 
    { 
     stopService(new Intent(this,MyService.class)); 
    } 

和MyService.java是

public class MyService extends Service{ 

    private static final String TAG = "MyService"; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onCreate"); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onStart"); 
    //Note: You can start a new thread and use it for long background processing from here. 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onDestroy"); 
    } 

} 

我有按鈕來啓動和停止服務和它的作品。現在我想讓該服務創建通知,正如我在文章開頭提到的那樣。我怎樣才能做到這一點?

回答

3

您可以從PendingIntent開始和AlarmManager

Tutorial here

不要忘記添加可能性取消報警經理

mAlarmManager.cancel(pendingIntent); 

你也可能要攔截android.intent.action.BOOT_COMPLETED事件,使您的應用程序在重新啓動後立即啓動,如果您想按計劃啓動您的服務。

4

要在特定時間啓動服務,我建議您創建一個由報警觸發的BroadcastReceiver,該報警又將啓動您的服務。

先寫這樣一個BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver { 


    @Override 
    public void onReceive(final Context context, final Intent intent) { 
     context.startService(new Intent(context, MyService.class)); 
    } 


    /** 
    * Schedule the next update 
    * 
    * @param context 
    *   the current application context 
    */ 
    private static void scheduleServiceUpdates(final Context context) { 
     // create intent for our alarm receiver (or update it if it exists) 
     final Intent intent = new Intent(context, AlarmReceiver.class); 
     final PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

     // compute first call time 1 minute from now 
     Calendar calendar = Calendar.getInstance(); 
     calendar.add(Calendar.MINUTE, 10); 
     long trigger = calendar.getTimeInMillis(); 

     // set delay between each call : 24 Hours 
     long delay = 24 * 60 * 60 * 1000; 

     // Set alarm 
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC, trigger, delay, pending); 
     // you can use RTC_WAKEUP instead of RTC to wake up the device 
    } 
} 

然後你只需要調用scheduleServiceUpdate方法來啓動reccuring事件。如果您只使用RTC類型,則當警報觸發服務時,如果電話被鎖定,則不會等到設備被用戶解鎖。如果您使用RTC_Wakeup,服務將在給定時間準確啓動。

請注意,AlarmManager中還有其他方法可以觸發事件。

相關問題