2014-05-03 26 views
16

嗨我正在處理通過後臺服務設置用戶輸入日期和時間通知的應用程序。現在我想在每天下午6點設置通知/警報,要求用戶是否要添加其他條目? 我該如何做到這一點?我應該使用相同的後臺服務還是廣播接收器? 請給我更好的解決方案,教程將是一個好主意。 在此先感謝。如何在Android中通過後臺服務在特定時間每天重複通知

回答

46

首先設置報警管理如下

Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 18); 
calendar.set(Calendar.MINUTE, 30); 
calendar.set(Calendar.SECOND, 0); 
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT); 
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE); 
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); 

創建廣播接收器類「AlarmReceiver」在此提高 通知的onReceive

public class AlarmReceiver extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     long when = System.currentTimeMillis(); 
     NotificationManager notificationManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 

     Intent notificationIntent = new Intent(context, EVentsPerform.class); 
     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
       notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 


     Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

     NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
       context).setSmallIcon(R.drawable.applogo) 
       .setContentTitle("Alarm Fired") 
       .setContentText("Events to be Performed").setSound(alarmSound) 
       .setAutoCancel(true).setWhen(when) 
       .setContentIntent(pendingIntent) 
       .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}); 
     notificationManager.notify(MID, mNotifyBuilder.build()); 
     MID++; 

    } 

} 

和在清單文件時,用於註冊接收機AlarmReceiver等級:

<receiver android:name=".AlarmReceiver"/> 

通過警報管理器不需要特殊權限來引發事件。

+0

什麼是'mid'? – silverFoxA

+0

mid是通知ID的int數據類型。在類級變量中聲明該變量。 –

+1

is alaram a typo? –

1

N.V.Rao的答案是正確的,但不要忘了把receiver標籤應用標籤內的AndroidManifest.xml文件:

<receiver android:name=".alarm.AlarmReceiver" /> 
相關問題