我是通知新手。我成功生成了通知,但我想为通知编写click事件。如果我点击通知我想在我的项目中打开一个类。这是我的任务。
对于一般未决意图,我将打开活动,但我的任务是每30分钟广播运行一次。这将得到通知。
我编写了代码,但是当我点击时,我的应用程序没有打开。请查看我的代码一次。
MainActivity
public class MainActivity extends Activity
{
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
context = this;
sendBroadcastMethod(context);
}
private void sendBroadcastMethod(Context context)
{
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60), pendingIntent);
Toast.makeText(this, "Alarm Started", Toast.LENGTH_SHORT).show();
Log.e("Alaram", "Alarm Started");
}
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver{
private NotificationManager mNotificationManager;
Context context2;
@Override
public void onReceive(Context context, Intent intent) {
context2 = context;
callNotification();
}
private void callNotification()
{
mNotificationManager = (NotificationManager) context2.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context2);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("My notification");
mBuilder.setContentText("Hello World!");
mNotificationManager.notify(0,mBuilder.build());
}
}
它完全显示通知,但我可以在哪里为我的通知编写点击操作。如果我在接收器类构建器中写入不接受接收器意图形成的意图。
答案 0 :(得分:1)
在callNotification()方法中试试这个
Intent in = new Intent(context, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, in, 0);
mBuilder.setContentIntent(pendingIntent).setAutoCancel(true);
答案 1 :(得分:1)
将此块添加到您的callNotification
方法;
Intent notificationIntent = new Intent(this.context2, MainActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(this.context2, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
您可以为该PendingIntent添加标记。例如,在此示例中,添加了一个标志来更新当前活动。 祝你好运。