点击通知后接收信号

时间:2013-08-23 00:08:24

标签: android android-intent notifications broadcastreceiver android-pendingintent

我从MainActivity班级发出通知。当用户点击通知时,我想返回MainActivity课程并执行方法。我还想知道点击了哪个通知(假设我使用不同的id启动多个通知)。在这里我做了什么,它没有工作

内部MainActivity.class

private void showNotification(String title, String message, int id) {
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(message);

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.setAction("mAction");
    PendingIntent resultPendingIntent = PendingIntent.getBroadcast(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(id, mBuilder.build());
}

同一内MainActivity.class我创建一个BroadcastReceiver类但它从未被调用

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if(action.equals("mAction")) {
                //execute my method here
        }
    }        

}

我确实在MyBroadcastReceiver.class中添加了AndroidManifest.xml个接收者:

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

1 个答案:

答案 0 :(得分:0)

作为@Varun的建议,这里有如何解决我的问题。

showNotification我将.setAction替换为.putExtra并将.getBroadcast更改为.getActivity

    Intent resultIntent = new Intent(this, MainActivity.class);           
    resultIntent.putExtra("mAction", id); // put id here you know which notification clicked
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); // change getBroadcast to getActivity

不再需要MyBroadcastReceiver类而是在onCreate()中添加一些行来获得意图结果:

    if(getIntent().hasExtra("mAction")){
        Bundle extra = getIntent().getExtras();
        int id = extra.getInt("mAction");
        if(id == 1) {
            //do stuff
        }
    }