我有一個應用程序每天在確切時間處發送notification
和AlarmManager
。每當應用程序在Android中打開時都會發送通知
但它有一個錯誤。 每當應用程序打開時,都會發送通知。
我怎樣才能得到的通知是每天發送一次?謝謝
MAINACTIVITY
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
int d = Integer.valueOf(1440);
calendar.setTimeInMillis(System.currentTimeMillis());
Intent i = new Intent(MainActivity.this, Receiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, i, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * d, pendingIntent);
}
}
接收機
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent i = new Intent(context, MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
long[] vibrate = {100, 100, 200, 300};
notification.vibrate = vibrate;
notification.defaults = Notification.DEFAULT_ALL;
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
notificationManager.notify(0, notification);
}
}
比較你兩次。當你打開應用程序那個時間和你的固定時間,並比較兩者。如果它的平等,然後發送通知。 – Piyush 2015-03-13 09:08:21
@PiyushGupta我希望通知是自動發送的,雖然沒有打開這個應用程序。這是否使你的解決方案? – user4152 2015-03-13 09:12:20
但在此之前,您必須在您的應用處於前景時進行檢查。並且您的代碼位於onCreate()方法中,每次打開應用程序或返回到此活動時,都會調用接收器。 – Piyush 2015-03-13 09:13:24