12

放送受信機に通知を開始させることはできますか?

このコードを試しましたが、機能しません。

通知は作成されますが、クリックしても何も起こりません。

注:notificationIntentをMyBroadcastReceiver.classからアクティビティ(MainActivity.classなど)に変更すると、正常に機能します。

通知の作成:

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(
        Context.NOTIFICATION_SERVICE);

    int notificationIconId = XXXXXX
    Notification notification = new Notification(
        notificationIconId,
        XXXXXX,
        System.currentTimeMillis()
    );

    CharSequence contentTitle = XXXXXXX
    CharSequence contentText = XXXXXX

    Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notificationManager.notify(1,notification);

これがBroadcastReceiverです

public static class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
   /*
          */

 }
}

AndroidManifest.xmlの内部

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

1 に答える 1

36

あなたのコードから...

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

PendingIntentターゲットを作成するときBroadcastReceiverは、を使用する必要があります。を使用する必要はgetBroadcast(...)ありませんgetActivity(...)

StartedIntent.getBroadcast(コンテキストコンテキスト、int requestCode、インテントインテント、intフラグ)を参照してください

また、このようなものを作成しないでくださいIntent...

Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class);

これは、特定のクラスを対象とする明示的なものですIntent(通常は特定のActivityクラスを開始するために使用されます)。

Intent代わりに、次のような「アクション」を使用して「ブロードキャスト」を作成します。

Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);

マニフェスト<intent-filter>のセクションのセクションも指定する必要があります。<receiver android:name=".MyBroadcastReceiver" />

于 2012-06-07T23:15:42.270 に答える