我有两项活动。在第一个活动中,我设置了警报。现在,我想在5秒后触发并开始第二个活动。第二个活动推送通知。为此,我写了以下代码:
添加闹钟类:
public class NotificationClass extends ActionBarActivity
{
AlarmManager am;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_class);
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent in = new Intent(this,PushNotification.class);
//b. create pending intent
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(),0,in,0);
//c. set alarm for 5 seconds.
am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 5000,pi);
}
}
添加通知的类:
public class PushNotification extends ActionBarActivity
{
int notificationID = 11037;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_push_notification);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
Intent resultIntent = new Intent(this, NotificationClass.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationClass.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setAutoCancel(true);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
}
}
但是,我没有得到理想的结果。我想我在报警课上有一些问题。请帮我解决这个问题。我在android清单文件中需要什么?
答案 0 :(得分:0)
您需要子类化BroadcastReceiver并在清单文件中静态注册它,或者通过LocalBroadcastManager使用registerReceiver动态注册它。 BroadcastReceiver的onReceive()方法将在收到警报生成的意图时推送通知。
静态注册很简单:
<receiver android:name=".MyAlarmReceiver" />
然后将通知代码从PushNotification.onCreate()方法移动到MyAlarmReceiver.onReceive()方法。
请参阅BroadcastReceiver或BroadcastReceiver tutorial。
希望它有所帮助。