broadcastreceiver intent launch活动其他应用程序通知

时间:2016-11-06 20:36:19

标签: java android

我创建2个应用程序(appA,appB),从appA我发送消息到appB,在appB中捕获此消息并创建通知,但我想在我点击通知打开我的appA并查看我的消息。

的appA

public class MainActivity extends Activity {
TextView text;
Button send;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.editText);
    send = (Button) findViewById(R.id.button);


    View.OnClickListener Onlistbtn = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            intent = new Intent(view.getContext(),Main2Activity.class);
            intent.putExtra("com.example.abc.send_messege.broadcast.Message",text.getText().toString());
            intent.setAction("com.example.abc.send_messege.custom_action");
            sendBroadcast(intent);
        }
    };

    send.setOnClickListener(Onlistbtn);
}}

appB的

public class MyReceiver extends BroadcastReceiver {
private final static AtomicInteger c = new AtomicInteger(3);
public MyReceiver() {
}


@Override
public void onReceive(Context context, Intent intent) {
    String text = intent.getStringExtra("com.example.abc.send_messege.broadcast.Message");
    //Intent intent1 = new Intent(context, Main2Activity.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, 0);
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.alert_dark_frame)
                    .setContentTitle("My notification")
                    .setContentText(text)
                    .setContentIntent(pIntent)
                    .setAutoCancel(true);

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

    mNotificationManager.notify(getID(), mBuilder.build());


}
public static int getID() {
    return c.incrementAndGet();
}}

AndroidManifest appB

 <receiver
        android:name=".MyReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.example.abc.send_messege.custom_action" />
        </intent-filter>
    </receiver>

1 个答案:

答案 0 :(得分:1)

好的,你可以试试这个

我们正在创建PendingIntent将新意图传递给launch activity from another application(appA)

Intent intent = new Intent();

//com.colisa.broadcast is the package of another app
//com.colisa.broadcast.MainActivity is the actity to be launched
intent.setComponent(
   new ComponentName("com.colisa.broadcast","com.colisa.broadcast.MainActivity"));

然后您将其传递给PengingIntent.setContentIntent(intent)

我还没有做过这个,但我认为你可以intent.putExtra(key, message)并且在接收活动时可以通过(this post

获取该消息
if (null != getIntent().getExtras().getString(key)){
  // whatever
}