我正在尝试创建一个带有按钮(操作)的简单通知。我已经成功地显示了它并为我的操作创建了PendingIntent。我还创建了一个广播接收器,当点击我的操作时应该调用它。但是它的onReceive()方法没有被调用。我不知道为什么。我在AndroidManifest.xml中也注册了BroadcastReceiver。
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button notify = (Button) findViewById(R.id.notify);
notify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent dismissIntent = new Intent("action1");
dismissIntent.setAction("action1");
PendingIntent action1intent = PendingIntent.getBroadcast(MainActivity.this, (int) System.currentTimeMillis(), dismissIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_menu)
.setContentTitle("My notification")
.setContentText("Hello World!")
.addAction(R.drawable.ic_menu, "action 1", action1intent);
Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
});
}
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("log", "Receiving somthn");
String whichAction = intent.getAction();
if (whichAction.equals("action1")) {
MainActivity.makeToast("This is action 1", context);
}
}
}
public static void makeToast(String string, Context context) {
Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.orglce.notification">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name=".MainActivity$Receiver">
<intent-filter>
<action android:name="com.example.orglce.notification.BROADCAST" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
new Intent(this, Receiver.class)
。之前我已经使用了new Intent(this, MainActivity.class)
但它没有起作用,我只是没有想到我必须将意图与 Receiver.class 而不是 MainActivity.class 相关联。非常感谢! :) - orglce