Android 集成firebase 推送(FCM)

这篇具有很好参考价值的文章主要介绍了Android 集成firebase 推送(FCM)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1,集成firebase 基础

1>googleService文件

firebase 静默推送 android,推送,android

2>项目级gradle

firebase 静默推送 android,推送,android

3>app级gradlefirebase 静默推送 android,推送,android

firebase 静默推送 android,推送,android

4>setting 

firebase 静默推送 android,推送,android

2,推送相关

重点:
firebase 静默推送 android,推送,android

源文档:设置 Firebase Cloud Messaging 客户端应用 (Android) (google.com)

/**
 * 监听推送的消息
 * 三种情况:
 * 1,通知时:
 * 当应用处于前台的时候,推送的消息会走onMessageReceived方法,处于后台时走系统托盘。
 * 2,数据时:
 * 当应用处于前、后台的时候,会走onMessageReceived方法。
 * 3,通知且携带数据:
 * 当应用处于前台的时候,推送的消息会走onMessageReceived方法,处于后台时,通知走系统托盘,数据走Intent 的 extra 中(点击通知栏后)。
 */

1>清单文件

firebase 静默推送 android,推送,android

2>MyFirebaseMessagingService类

/**
 * 推送数据对通知的影响
 * 1,如果我们推送的数据 notification 对应的数据 不为空,那么我们接收消息就需要分为两种情况,
 * 前台和后台,如果App当前状态为前台,那么 onMessageReceived 方法就会被调用,
 * 后续我们自己拿到对用的数据进行通知栏的显示,如果App当前状态为后台的话 那么我们无需自己写 sdk会自己弹出。
 *
 *,2,如果我们推送的数据 notification 对应的数据为空,把所有的数据放置到data 字段里面,
 * 那么sdk不会为我们弹出通知,这时候无论App在前台还是后台都会调用 onMessageReceived ,
 * 这时候我们自己需要处理通知栏的ui 显示。这种情况一般用于自定义通知栏ui 的时候。
 */

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    /**
     * 监听推送的消息
     * 三种情况:
     * 1,通知时:
     * 当应用处于前台的时候,推送的消息会走onMessageReceived方法,处于后台时走系统托盘。
     * 2,数据时:
     * 当应用处于前、后台的时候,会走onMessageReceived方法。
     * 3,通知且携带数据:
     * 当应用处于前台的时候,推送的消息会走onMessageReceived方法,处于后台时,通知走系统托盘,数据走Intent 的 extra 中(点击通知栏后)。
     */
    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {

        String testDemo = "0";//测试数据,后端自定义消息/或控制台测试时输入键值,时传递来 “键”-“值” 中的 值
//        Map<String, String> remoteMessageMap = message.getData();
        if (message.getData() != null && !message.getData().isEmpty()) {//不自定义消息,getData为空
            if (message.getData().size() > 0) {
                testDemo = message.getData().get("testDemo");//“键”-“值” 中的 键

            }
        }

        if (message.getNotification() != null && !message.getNotification().getTitle().isEmpty() && !message.getNotification().getBody().isEmpty()) {
//            sendNotification(message.getNotification().getTitle(), message.getNotification().getBody(), testDemo);
            String click_action = message.getNotification().getClickAction();
            sendNotification(message.getNotification().getTitle(), message.getNotification().getBody(), testDemo, click_action);
        }


    }


    /**
     * 当有新的Firebase token 时的回调
     * 第一次安装app 获取到的 pushtoken
     */
    @Override
    public void onNewToken(@NonNull String token) {
        //token 传递给后端!!
        Log.e("测试", "onNewToken =" + token);
    }

    /**
     * 自定义通知
     *
     * @param messageBody
     */
    private void sendNotification(String messageTitle, String messageBody, String testDemo, String click_action) {
        Intent intent = prepareIntent(click_action);
//    private void sendNotification(String messageTitle, String messageBody, String testDemo) {
//        Intent intent = new Intent(this, MainActivity.class);

        String channelID = getResources().getString(R.string.default_notification_channel_id);//渠道ID
        String channelName = getResources().getString(R.string.default_notification_channel_name);//渠道名称

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (testDemo != null && !testDemo.isEmpty()) {
            intent.putExtra("testDemo", testDemo);

        }

        int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueInt /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder notificationBuilder;
        //android 8 开始要 创建通知渠道,否则通知栏不弹出
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationBuilder = new NotificationCompat.Builder(this, channelID);
            NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        } else {
            notificationBuilder = new NotificationCompat.Builder(this);
        }

        //设置title
        if (messageTitle != null && !messageTitle.isEmpty()) {
            notificationBuilder.setContentTitle(messageTitle);
        } else {
            notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
        }

        //设置body
        if (messageBody != null && !messageBody.isEmpty()) {
            notificationBuilder.setContentText(messageBody);
        }
//        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notificationBuilder
                .setSmallIcon(R.drawable.icon_return)//设置通知栏的小图标,必需设置,否则crash
                .setAutoCancel(true)//点击通知后,通知自动消失
                .setWhen(System.currentTimeMillis())// 设置通知时间,此事件用于通知栏排序
                .setPriority(NotificationCompat.PRIORITY_HIGH)// 设置优先级,低优先级可能被隐藏
//                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);//设置通知栏被点击时的事件

        notificationManager.notify(uniqueInt /* ID of notification */, notificationBuilder.build());

    }

    public Intent prepareIntent(String clickAction) {
        Intent intent;
        boolean isAppInBackground;
        isAppInBackground = ProcessJudgmentHelper.isRunBackground(this);
        if (isAppInBackground) {
            intent = new Intent(this, MainActivity.class);
        } else {
            intent = new Intent(clickAction);
        }

        return intent;
    }

    /**
     * 1,如果未开启通知,则跳转到通知设置界面,点击之后就需要跳转到 APP的通知设置界面,
     * 对应的Action是:Settings.ACTION_APP_NOTIFICATION_SETTINGS, 这个Action是 API 26 后增加的。
     * 2,如果在部分手机中无法精确的跳转到APP对应的通知设置界面,我们就考虑直接跳转到APP信息界面,
     * 对应的Action是:Settings.ACTION_APPLICATION_DETAILS_SETTINGS。
     *
     */

}

4>主启动Activity(清单文件里设置 <action android:name="android.intent.action.MAIN" /> 的Activity)


/**
 * 1,清单文件里设置 <action android:name="android.intent.action.MAIN" /> 的Activity,一般是Splish 闪屏页。
 * 在onCreate() 方法里 获取用户PushToken,调用接口传给自己的后端,以防有变化。
 * 2,如果是自定义消息(当后端或者控制台设置响应的data 键值)在onResume() 方法里 使用intent 获取到对应的值,进行相关操作,
 * 例如:根据约定值 进行响应页面的跳转。
 *
 *
 */
public class MainActivity extends AppCompatActivity {

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

        requestPer();

        try {
            boolean goolgePlayServiceAvailable = FirebaseManager.getInstance().isGoolgePlayServiceAvailable(this);
            if (goolgePlayServiceAvailable) {
                uploadPushToken();
            } else {
                Log.e("测试", "谷歌服务不可用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("测试", "谷歌服务异常");

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        //当后端或者控制台设置自定义消息后,点击通知时能获取到对应的值
        String testDemo = intent.getStringExtra("testDemo");

        if (testDemo != null && !testDemo.isEmpty()) {
            //如有特殊情形,要判断是否登录,没登录跳转登录页
//            if(){
//            }
            if (testDemo.equals("66")) {
                Intent intentSeconActivity = new Intent(this, SeconActivity.class);
                startActivity(intentSeconActivity);
                finish();
            }
        }

    }

    /**
     * 上传push token
     * 正常情况下每次启动 都会获取到!
     */
    private void uploadPushToken() {
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.e("测试", "Fetching FCM registration token failed", task.getException());
                            return;
                        }

                        // Get new FCM registration token
                        String token = task.getResult();
                        Log.e("测试", "MainActivity token =" + token);

                    }
                });
    }

    /**
     * android 高版本请求推送权限
     */
    private void requestPer() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.POST_NOTIFICATIONS)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {

                        } else {
                        }
                    }
                });
    }
}

==================结束===============

工具方法:
 文章来源地址https://www.toymoban.com/news/detail-855229.html

    /** 判断程序是否在后台运行 */
    public static boolean isRunBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 表明程序在后台运行
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }

到了这里,关于Android 集成firebase 推送(FCM)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flutter集成Mob推送(Android)

    Mob推送 Flutter对接文档 1、在pubspec.yaml文件中加入下面依赖 2、导入 MobPush 相关依赖 在项目根目录的build.gradle中添加以下代码: 3、在 /android/app/build.gradle 中添加以下代码: 4、平台相关集成 在项目的/android/app/build.gradle中添加: 5、在MainActivity的onCreate中添加以下代码: SDK API

    2024年02月02日
    浏览(29)
  • 通过Android Logcat分析firebase崩溃

    参考:UnityIL2CPP包Crash闪退利用Android Logcat还原符号表堆栈日志 - 简书 1、新建空白unity工程,打开PackageManager窗口,菜单栏Window/PackageManager 2、PackageManager中安装Android Logcat日志工具 3、安装AndroidLogcat完成 1.打包 在出包时勾选Create symbols.zip选项,在PlayerSettings面板中,出包选项从

    2024年01月25日
    浏览(32)
  • Unity Android FireBase bugly报错查询

    报错如下图,注意,标红的三处 使用的il2cpp和架构是arm64-v8a 那我们就可以根据这些去找对应的符号表,在unity安装目录下,也可以从安卓apk中解压出来 找到libunity.sym.so。拷贝到下一步的NDK目录下。 找到NDK中arm-linux-androideabi-addr2line.exe目录 效果如下:

    2024年02月03日
    浏览(41)
  • Android11.0系统中实现静默安装并启动App以及静默卸载

    本文描述Android11中通过修改系统PackageInstaller应用支持静默安装App,并启动安装的App。 PackageInstaller是系统中专门负责app安装的App,静默安装逻辑添加到此应用中,应用所在路径 /frameworks/base/packages/PackageInstaller/src/com/android/packageinstaller/ 添加SilenceInstallManager,路径为 /frameworks

    2024年02月03日
    浏览(49)
  • 【干货】Android系统定制基础篇:第三部分(Android静默安装、Android支持usb打印机)

    一些产品要求APP在升级时能够实现静默安装,而无需弹出安装界面让用户确认。这里提出两种实现方案: 方案一 APP调用『pm』命令实现静默安装,此方案无须修改Android源码,但需要root权限。 方案二 修改Android PackageInstaller 源码,增加Intent参数来指定是否要静默安装,同时支

    2024年02月10日
    浏览(32)
  • Android APK 签名打包原理分析(三)【静默安装的实现方案】

    小编目前从事的系统定制类工作,有客户提出了,需要后台“静默安装”他们的app,也就是悄无声息的安装,而且特别强调,不可以跳出任何安装引导页面,他们的app下载完成之后,后台调用公开的android install代码,系统就后台完成安装,安装完成之后,重新打开应用就可以

    2024年02月01日
    浏览(47)
  • 环信IM Android端实现华为推送详细步骤

    首先我们要参照华为的官网去完成 ,以下两个配置都是华为文档为我们提供的 1.https://developer.huawei.com/consumer/cn/doc/HMSCore-Guides/android-config-agc-0000001050170137#section19884105518498 2.https://developer.huawei.com/consumer/cn/doc/HMSCore-Guides/android-integrating-sdk-0000001050040084 3.在环信上传华为的配置信

    2024年02月21日
    浏览(27)
  • Android 实现MQTT客户端,用于门禁消息推送

    添加MQTT依赖 implementation ‘org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2’ implementation ‘org.eclipse.paho:org.eclipse.paho.android.service:1.1.1’ 在Manifest清单文件中添加服务 MqttClient的实现方式 MQTT初始化连接线程,实现与服务器的连接、订阅、发布消息 MQTT重连 MQTT断开 发送消息 MqttAndroid

    2024年02月14日
    浏览(37)
  • Android,ios,安卓app推送消息通知,java后台向手机推送app的通知教程

    个推是商用级的移动应用消息推送云服务供应商,客户端 SDK 支持 Android 和 iOS 两大平台,开发者集成 SDK 后,可以通过个推强大的 web 端及丰富的 API 开放接口,发送推送消息、统计分析推送效果。可有效提高 App 活跃度,增加用户留存率。 如果您还没有个推 账号,可在 个推

    2024年02月04日
    浏览(32)
  • Android Studio App开发之通知推送Notification的讲解及实战(给用户推送信息实战)

    运行有问题或需要全部资源请点赞关注收藏后评论区留言~~~ 在APP的运行过程中,为了让用户及时收到某些消息,有必要由App主动向用户推送消息通知,以免错过有价值的信息。 在手机屏幕的顶端下拉会弹出通知栏,里面存放的便是App主动推给用户的提醒消息,消息通知的组

    2023年04月08日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包