栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android 接收推送消息跳转到指定页面的方法

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 接收推送消息跳转到指定页面的方法

问题的提出

本次接入的是个推,其他家的推送没有研究过,思路应该是类似的

App在前台,这个时候需要弹出一个对话框,提醒用户有新的消息,是否要查看,查看的话跳转到指定页面

App在后台,或是App进程已经被系统回收,收到推送后App进程会被个推拉起。这时候要展示通知,点击通知栏打开App并跳转到目标页面,关闭目标页面后需要返回到应用首页,而不是直接推出App

实现思路

App在前台时,弹出Dialog提醒用户有新消息,但是最新版的个推文档接收推送消息是继承IntentService,无法获取弹出Dialog所需要的Context(注意不能用getApplicationContext()),所以采用Dialog样式的Activity来实现

App在后台时,如果直接在PendingIntent中传目标Activity的Intent,则在退出目标Activity时会直接退出应用,感觉像是闪退了一样;如果是跳转到首页,然后在首页中检测是否是由点击通知进入应用的来进行跳转,这样的话首页就会闪屏。综上方法都不是很理想,一个比较好的解决方案是给PendingIntent传递一个Intent数组,分别放置目标Activity和首页,这样效果比较好

App在前台时,弹出Dialog样式的Activity

设置Activity样式


  false
  @null
  true //去掉标题
  @android:color/transparent //背景透明
  true //设置触摸弹框外面是否会消失
  true
  @null
  true

AndroidManifest.xml


此处需要注意的是这里的Activity继承的是AppCompatActivity,如果是继承Activity,则一些属性设置需要微调,比如去掉标题要改为

true

以上设置以后还需要设置弹框的大小

public class alertDialogActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_activity);
    
    //设置弹框大小,此处宽度为屏幕宽度减去160像素
    getWindow().setLayout(DeviceUtil.getDisplayParametersW(this)-160, ViewGroup.LayoutParams.WRAP_CONTENT);
    getWindow().setGravity(Gravity.CENTER);

    initView();
  }
}

App在后台或是已经被销毁

我们在接收到推送消息时都会弹出通知,这里只需要对常用的弹出通知方式进行微调一下

//关键的地方
PendingIntent contentIntent = PendingIntent.getActivities(context, 0, intents, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
    //省略其他的一些设置
    .setContentIntent(contentIntent)
    //省略其他的一些设置
    
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify((int) System.currentTimeMillis() / 1000, notification);

上面关键的改动就在PendingIntent,里面的intents参数存放首页Activity和目标Activity,比如

Intent[] intents = new Intent[2];
Intent intent_main = new Intent(getApplicationContext(), MainActivity.class);
Intent intent_target = new Intent(getApplicationContext(), TargetActivity.class);

intents[0] = intent_main;
intents[1] = intent_target;

通过以上的设置后,点击通知栏就会打开TargetActivity,从TargetActivity返回后会打开MainActivity,而不会直接退出

需要注意的是,MainActivity需要设置启动模式为singleInstance
AndroidManifest.xml



以上就是接收推送消息后的跳转的一些内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/156676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号