我正在嘗試使用爲其定義的按鈕(操作)創建一個簡單的通知。我已經設法正確顯示它併爲我的操作創建一個PendingIntent。我還創建了一個BroadcastReceiver,當我的操作被點擊時應該被調用。但是它的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>
是的,它的工作!更改爲'新的意圖(這,Receiver.class)'。以前我已經有了'新的Intent(this,MainActivity.class)',但它不起作用,它不會讓我想到我必須將意圖與Receiver.class而不是MainActivity.class關聯起來。非常感謝! :) – orglce