我想在一段时间间隔后自动显示和安卓通知
我使用了以下all suggested code snippets
但是我在{5}分钟之后failed to get automatic notification
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = "Hellooo, alrm worked ----";
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(context, TripNotification.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
public void setAlarm(Context context){
Log.d("Carbon","Alrm SET !!");
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add 30 seconds to the calendar object
cal.add(Calendar.SECOND, 30);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
}
<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>
答案 0 :(得分:1)
我建议你写一个Activity
。在onCreate()方法中每隔5分钟设置一次警报,如下所示:
Intent intent = new Intent(this, ServiceForAlarm.class);
intent.setAction(""+System.currentTimeMillis());
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(m_Context, 0, intent, Intent.FLAG_GRANT_READ_URI_PERMISSION);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 300000L, pendingIntent);
在ServiceForAlarm
中,编写推送通知的代码。
public class ServiceForAlarm extends Service {
private Context mContext;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mContext = getApplicationContext();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
SetNotification();
stopSelf();
}
private void SetNotification() {
m_NotificationManager = (NotificationManager)m_Context.getSystemService(Context.NOTIFICATION_SERVICE);
m_Notification = new Notification(R.drawable.icon_app, "Your message", System.currentTimeMillis());
m_Intent = new Intent() ;
m_PendingIntent = PendingIntent.getActivity(m_context, 0, m_Intent, 0);
m_Notification.contentIntent = m_PendingIntent;
m_Notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
m_Notification.setLatestEventInfo(m_context, "Title", "Click me", m_PendingIntent);
m_NotificationManager.notify(1010, m_Notification);
}
}