0

I fire a notification from MainActivity class. When user click the notification, i'd like to return back to MainActivity class and execute a method. I'd also like to know which notification is clicked (Assuming that i fire multiple notifications with different id). Here what i did and it didn't work

Inside 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());
}

Same inside MainActivity.class i create a BroadcastReceiver class but it never got called:

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
        }
    }        

}

I did add MyBroadcastReceiver.class receiver in AndroidManifest.xml:

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

1 回答 1

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
        }
    }
于 2013-08-23T01:11:11.370 回答