android - 如何在点击推送通知时打开新 Activity ?

标签 android push-notification

我正在开发一个 android 应用程序,我需要在其中接收多个通知,每个通知都包含唯一的数据。

我已经完成的事情 1.使用gcm服务接收多个通知 2.在新的activity中显示点击通知时服务器发送的数据

问题: 假设我收到了三个通知,每个通知都有唯一的数据。当我点击一个通知时,一个新的 Activity 开始于该通知中的数据。所以现在接收通知 Activity 正在运行。现在,如果我单击第二个通知,则接收通知 Activity 会加载旧数据(来自第一个通知的数据)。如果我关闭应用程序并单击第三个通知,则接收通知 Activity 会加载来自第三个通知的数据,这是应该的。

我试过:

  1. 将 Intent 标志设置为 FLAG_ACTIVITY_CLEAR_TOP(不起作用)
  2. 编辑 list 文件以包含 android:launchMode="singleInstance"但没有成功

我正在使用

resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

在 intentservice 中和在 list 文件中添加 android:launchMode="singleInstance" 都不起作用。

Intent 服务类

public class GcmIntentService extends IntentService{

Context context;
public static int notify_no=0;

//System.currentTimeMillis();

private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM NOTIFICATION";

public GcmIntentService() {
    super("GcmIntentService");
    // TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);


     if (!extras.isEmpty()) {

         if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Send error: " + extras.toString());
             sendNotification(this,msg);
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Deleted messages on server: " +
               //         extras.toString());
                sendNotification(this,msg);
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i=0; i<5; i++) {
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                //sendNotification("Received: " + extras.toString());
               // sendNotification(RegIdDTO.REG_ID,msg);
                sendNotification(this,msg);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
     GcmBroadcastReceiver.completeWakefulIntent(intent);
}


private static void sendNotification(Context context,String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationCompat.Builder nBuilder;
    Uri alarmSound = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    nBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("header")
            .setLights(Color.BLUE, 500, 500).setContentText(message)
            .setAutoCancel(true).setTicker("Notification from Traffic")
            .setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
            .setSound(alarmSound)
            ;

    String consumerid = null;
    Integer position = null;
           // write your click event here
       Intent resultIntent = new Intent(context, NotificationReceiveActivity.class);

       resultIntent.putExtra("message", message);
      // resultIntent.setData(Uri.parse("content://"+when));
       resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

 PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
        notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Show the max number of notifications here
  if (notify_no < 9) {
    notify_no = notify_no + 1;
  } else {
    notify_no = 0;
  }
nBuilder.setContentIntent(resultPendingIntent);
NotificationManager nNotifyMgr = (NotificationManager) context
        .getSystemService(context.NOTIFICATION_SERVICE);
  nNotifyMgr.notify(notify_no + 2, nBuilder.build());
  }

}

接收 Activity

public class NotificationReceiveActivity extends Activity {

    TextView name;
    TextView deal;
    TextView valid;
    TextView address;
    JSONObject json;
    GcmIntentService serv;
    Context mContext;
  //  static boolean active = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_receive);


    Intent intent = getIntent();

    name = (TextView) findViewById(R.id.name);
    deal = (TextView) findViewById(R.id.deal);
    valid = (TextView) findViewById(R.id.valid);
    address = (TextView)findViewById(R.id.address);
    String message = intent.getExtras().getString("message");

    try {
        json = new JSONObject(message);
        String stime = json.getString("name");
        name.setText(stime);

        String slecturename = json.getString("deal");
        deal.setText(slecturename);

        String sroom = json.getString("valid");
        valid.setText(sroom);

        String sfaculty = json.getString("address");
        address.setText(sfaculty);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    serv=new GcmIntentService();
    //serv.CancelNotification(getApplicationContext());

}
}

使用上面的代码我能够收到通知,问题是如果我的 Activity 不在运行状态并且我收到通知。此时,如果我从通知中打开 Activity ,它会显示新数据,但如果 Activity 正在运行并且通知同时到达。如果我打开此通知,则它正在加载旧数据的 Activity 。即使我正在运行 Activity ,我也想在 Activity 中显示新数据。

最佳答案

当您获得一个新的 Intent 并且您的 Activity 使用 singleTop 或 Intent 使用 FLAG_ACTIVITY_SINGLE_TOP 时,您的新 Intent 实际上会传送到 Activity 的 onNewIntent .引用文档:

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

因此,如果您在 NotificationReceiveActivity 中覆盖该方法,您的问题应该得到解决。

关于android - 如何在点击推送通知时打开新 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22195701/

相关文章:

android - 使用 SELECT 的结果在 Spinner 中选择一个选项?

android - 我的应用程序在 android 模拟器中运行良好,但在我的真实设备中无法运行

php - FCM 链接在桌面通知中不起作用

javascript - 服务 worker 的推送事件未被调用

android - 使用 c2dm 一次发送多个推送

java - 打开跟踪文件时出错:没有这样的文件或目录| java.lang.ClassNotFoundException:net.sourceforge.jtds.jdbc.Driver

屏幕关闭的 Android Timer/Handler/Thread.sleep() 无法正常工作

android - 如何检查蓝牙是否以编程方式启用?

push-notification - 为什么在 Web 推送库上使用推送通知服务?

android - 据称随机获取 "No permission to send message to these tmIDs"HMS 推送服务