我从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>
答案 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
}
}