219

通知からアクティビティにパラメーターを送信する方法を見つけることができます。

通知を作成するサービスがあります。ユーザーが通知をクリックすると、いくつかの特別なパラメーターを使用してメイン アクティビティを開きたいと思います。たとえば、アイテム ID を使用すると、アクティビティで特別なアイテムの詳細ビューを読み込んで表示できます。より具体的には、ファイルをダウンロードしています。ファイルがダウンロードされたときに、クリックするとアクティビティが特別なモードで開かれるという通知が必要です。意図的に使用しようとしputExtraましたが、それを抽出できないように見えるので、間違っていると思います。

通知を作成する私のサービスからのコード:

        // construct the Notification object.
     final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());


    final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
    contentView.setImageViewResource(R.id.image, R.drawable.icon);
    contentView.setTextViewText(R.id.text, tickerText);
    contentView.setProgressBar(R.id.progress,100,0, false);
    notif.contentView = contentView;        

    Intent notificationIntent = new Intent(context, Main.class);
    notificationIntent.putExtra("item_id", "1001"); // <-- HERE I PUT THE EXTRA VALUE
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notif.contentIntent = contentIntent;

    nm.notify(id, notif);

通知から追加のパラメーターを取得しようとするアクティビティのコード:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);


    Bundle extras = getIntent().getExtras();
    if(extras != null){
        Log.i( "dd","Extra:" + extras.getString("item_id") );
    }

エクストラは常に null であり、ログには何も記録されません。

ところで...onCreateアクティビティが開始されたときにのみ実行されます。アクティビティがすでに開始されている場合は、エクストラを収集し、受け取ったitem_idに従ってアクティビティを提示したいと考えています。

何か案は?

4

13 に答える 13

252

このガイド(通知の作成)を参照し、ApiDemosの「StatusBarNotifications」と「NotificationDisplay」のサンプルを確認してください。

アクティビティがすでに実行されているかどうかを管理するには、次の2つの方法があります。

  1. アクティビティの起動時にFLAG_ACTIVITY_SINGLE_TOPフラグをインテントに追加 し、アクティビティクラスで onNewIntent(Intent intent)イベントハンドラーを実装します。これにより、アクティビティに対して呼び出された新しいインテントにアクセスできます(これは、getIntentを呼び出すだけではありません)。 ()、これは常にアクティビティを開始した最初のインテントを返します。

  2. ナンバーワンと同じですが、インテントにフラグを追加する代わりに、アクティビティAndroidManifest.xmlに「singleTop」を追加する必要があります。

インテントエクストラを使用する場合はPendingIntent.getActivity()、フラグを使用して呼び出すことを忘れないでくださいPendingIntent.FLAG_UPDATE_CURRENT。そうしないと、すべての通知で同じエクストラが再利用されます。

于 2009-07-29T15:50:39.157 に答える
102

私のアプリケーションがメッセージ通知を表示する同様の問題がありました。複数の通知があり、各通知をクリックすると、その通知の詳細がメッセージ表示アクティビティに表示されます。ビューメッセージインテントで同じ余分なパラメーターが受信されるという問題を解決しました。

これを修正したコードは次のとおりです。通知インテントを作成するためのコード。

 Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
    notificationIntent.putExtra("NotificationMessage", notificationMessage);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);

ビュー メッセージ アクティビティのコード。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    onNewIntent(getIntent());
}

@Override
public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    if(extras != null){
        if(extras.containsKey("NotificationMessage"))
        {
            setContentView(R.layout.viewmain);
            // extract the extra-data in the Notification
            String msg = extras.getString("NotificationMessage");
            txtView = (TextView) findViewById(R.id.txtMessage);
            txtView.setText(msg);
        }
    }


}
于 2012-08-07T07:11:44.473 に答える
32

少し遅いかもしれませんが、これの代わりに:

public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    Log.i( "dbg","onNewIntent");

    if(extras != null){
        Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
        Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));

    }
    mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}

これを使って:

Bundle extras = getIntent().getExtras();
if(extras !=null) {
    String value = extras.getString("keyName");
}
于 2010-12-08T23:36:06.267 に答える
19

ここで同じ問題が発生します。異なるリクエストコードを使用して解決し、PendingIntentを作成するときに通知と同じIDを使用します。しかし、なぜこれを行う必要があるのか​​まだわかりません。

PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(**id**, notif);
于 2011-01-26T13:57:23.733 に答える
16

いくつかのメーリングリストや他のフォーラムを読んだ後、このトリックが意図にいくつかのユニークなデータを追加しているように見えることがわかりました.

このような:

   Intent notificationIntent = new Intent(Main.this, Main.class);
   notificationIntent.putExtra("sport_id", "sport"+id);
   notificationIntent.putExtra("game_url", "gameURL"+id);

   notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime()))); 

なぜこれを行う必要があるのか​​ わかりません。エクストラだけでは識別できない意図と関係があります...

于 2009-08-10T21:21:27.853 に答える
5

AndroidManifest.xml

launchMode="singleTop" を含める

<activity android:name=".MessagesDetailsActivity"
        android:launchMode="singleTop"
        android:excludeFromRecents="true"
        />

SMSReceiver.java

Intent と PendingIntent のフラグを設定する

Intent intent = new Intent(context, MessagesDetailsActivity.class);
    intent.putExtra("smsMsg", smsObject.getMsg());
    intent.putExtra("smsAddress", smsObject.getAddress());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

MessageDetailsActivity.java

onResume() - 毎回呼び出され、エクストラをロードします。

Intent intent = getIntent();
    String extraAddress = intent.getStringExtra("smsAddress");
    String extraBody = intent.getStringExtra("smsMsg");

それが役立つことを願っています。これはstackoverflowに関する他の回答に基づいていましたが、これは私にとって最も更新されたものです。

于 2016-04-26T14:06:33.253 に答える
4

簡単です。これがオブジェクトを使用した私のソリューションです。

私のPOJO

public class Person implements Serializable{

    private String name;
    private int age;

    //get & set

}

メソッド通知

  Person person = new Person();
  person.setName("david hackro");
  person.setAge(10);

    Intent notificationIntent = new Intent(this, Person.class);
    notificationIntent.putExtra("person",person);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.notification_icon)
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
                .setPriority(2)
                .setLargeIcon(bm)
                .setTicker(fotomulta.getTitle())
                .setContentText(fotomulta.getMessage())
                .setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                .setWhen(System.currentTimeMillis())
                .setContentTitle(fotomulta.getTicketText())
                .setDefaults(Notification.DEFAULT_ALL);

新しい活動

 private Person person;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_push);
    person = (Person) getIntent().getSerializableExtra("person");
}

幸運を!!

于 2016-05-02T15:27:36.963 に答える
3

いくつかの検索を行った後、Android開発者ガイドから解決策を得ました

PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

stackBuilder.addParentStack(ArticleDetailedActivity.class);

contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

Test Activity クラスで Intent の追加の値を取得するには、次のコードを記述する必要があります。

 Intent intent = getIntent();
 String extra = intent.getStringExtra("extra") ;
于 2016-05-20T12:38:14.830 に答える
0

使用する場合

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

アクティビティを起動するための AndroidManifest.xml ファイルで、インテントで次を使用する必要があります。

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

重要なのは、一意のデータを設定することです。たとえば、次のような一意の ID を使用します。

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
于 2016-10-13T08:12:22.560 に答える