草庐IT

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

coder 2023-12-04 原文

我正在开发一个 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 - 如何在点击推送通知时打开新 Activity ?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  10. ruby-on-rails - 如何在 ruby​​ 交互式 shell 中有多行? - 2

    这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式ruby​​shell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f

随机推荐