XiaomiPushDemo【小米推送集成,基于V3.6.12版本】
版权声明:本文为HaiyuKing原创文章,转载请注明出处!
前言
这个Demo只是记录小米推送的集成,不能运行。
使用步骤
一、项目组织结构图
注意事项:
1、 导入类文件后需要change包名以及重新import R文件路径
2、 Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖
二、导入步骤
2.1、接入准备
参考官网《小米推送服务启用指南》
注册小米开发者账号——》启用推送
2.2、下载SDK
下载地址:http://admin.xmpush.xiaomi.com/mipush/downpage/
下载后的压缩包解压后的目录:
2.3、集成SDK
为了便于管理,我在Demo中新建了一个ThirdLib的module,用于集成SDK。
(1)新建ThirdLib的module,并在app的build.gradle中引用
//引用thirdlib
implementation project(':thirdlib')
(2)在ThirdLib这个module中集成SDK
复制MiPush_SDK_Client_x_x_x.jar到工程 libs/ 目录下;
因为是在thirdlib这个module中集成jar包,所以还需要在thirdlib这个module的build.gradle文件中引用libs目录下的jar包。
//小米推送SDK
api files('libs/MiPush_SDK_Client_3_6_12.jar')
(3)在ThirdLib这个module的res/strings.xml文件中添加以下代码(用于自定义的XiaomiMessageReceiver中调用)
<resources> <string name="app_name">ThirdLib</string> <!--=====================================小米推送SDK=====================================--> <string name="recv_passthrough_message"> Receive a passthrough message. Content is \"%1$s\"</string> <string name="click_notification_message"> Clicked a notification message. Content is \"%1$s\"</string> <string name="arrive_notification_message"> Arrived a notification message. Content is \"%1$s\"</string> <string name="register_success">Register push success.</string> <string name="register_fail">Register push fail.</string> <string name="set_alias_success"> Set alias \"%1$s\" success.</string> <string name="set_alias_fail"> Set alias fail for %1$s.</string> <string name="unset_alias_success"> Unset alias \"%1$s\" success.</string> <string name="unset_alias_fail"> Unset alias fail for %1$s.</string> <string name="set_account_success"> Set account \"%1$s\" success.</string> <string name="set_account_fail"> Set account fail for %1$s.</string> <string name="unset_account_success"> Unset account \"%1$s\" success.</string> <string name="unset_account_fail"> Unset account fail for %1$s.</string> <string name="subscribe_topic_success"> Subscribe topic \"%1$s\" success.</string> <string name="subscribe_topic_fail"> Subscribe topic fail for %1$s.</string> <string name="unsubscribe_topic_success"> Unsubscribe topic \"%1$s\" success.</string> <string name="unsubscribe_topic_fail"> Unsubscribe topic fail for %1$s.</string> <string name="set_accept_time_success"> Set accept time %1$s - %2$s success.</string> <string name="set_accept_time_fail"> Set accept time fail for %1$s.</string> </resources>
(4)配置 AndroidManifest.xml【注意是app这个module中的,不是thirdlib这个module中的】
注意下面标记橙色代码:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.why.project.xiaomipushdemo"> <!-- ======================小米推送SDK====================== --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <!-- the following 2 com.xiaomi.mipushdemo should be changed to your package name --> <permission android:name="${applicationId}.permission.MIPUSH_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="${applicationId}.permission.MIPUSH_RECEIVE" /> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <!-- ======================小米推送SDK========================== --> <service android:name="com.xiaomi.push.service.XMJobService" android:enabled="true" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" android:process=":pushservice" /> <service android:name="com.xiaomi.push.service.XMPushService" android:enabled="true" android:process=":pushservice" /> <service android:name="com.xiaomi.mipush.sdk.PushMessageHandler" android:enabled="true" android:exported="true" /> <service android:name="com.xiaomi.mipush.sdk.MessageHandleService" android:enabled="true" /> <!--自定义一个BroadcastReceiver类:为了接收消息--> <receiver android:name="com.why.project.xiaomipushdemo.xiaomipush.XiaomiMessageReceiver" android:exported="true"> <intent-filter> <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" /> </intent-filter> <intent-filter> <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" /> </intent-filter> <intent-filter> <action android:name="com.xiaomi.mipush.ERROR" /> </intent-filter> </receiver> <receiver android:name="com.xiaomi.push.service.receivers.NetworkStatusReceiver" android:exported="true"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> <receiver android:name="com.xiaomi.push.service.receivers.PingReceiver" android:exported="false" android:process=":pushservice"> <intent-filter> <action android:name="com.xiaomi.push.PING_TIMER" /> </intent-filter> </receiver> </application> </manifest>
(5)在项目中添加xiaomipush包中的文件
1、PermissionActivity中需要用到自定义MyApplication中的代码,下一步中会增加,这里报错不用管;
2、XiaomiMessageReceiver中使用的到字符串资源在thirdLib中的res/strings.xml文件中定义了;
3、XiaomiMessageReceiver主要通知、消息的回调
(6)初始化SDK
在MyApplication中执行
package com.why.project.xiaomipushdemo; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.os.Process; import com.xiaomi.mipush.sdk.MiPushClient; import java.util.List; /** * Created by HaiyuKing * Used */ public class MyApplication extends Application { /*=================小米推送SDK=====================*/ // user your appid the key. private static final String APP_ID = "28823037343464645735"; // user your appid the key. private static final String APP_KEY = "56545654754865"; @Override public void onCreate() { super.onCreate(); initXiaoMiPush(); } //小米推送SDK private void initXiaoMiPush(){ // 注册push服务,注册成功后会向DemoMessageReceiver发送广播 // 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息 if (shouldInit()) { MiPushClient.registerPush(this, APP_ID, APP_KEY); } } //小米推送SDK【用于PermissionActivity中调用】 public static void reInitPush(Context ctx) { MiPushClient.registerPush(ctx.getApplicationContext(), APP_ID, APP_KEY); } //小米推送SDK相关 private boolean shouldInit() { ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); String mainProcessName = getPackageName(); int myPid = Process.myPid(); for (ActivityManager.RunningAppProcessInfo info : processInfos) { if (info.pid == myPid && mainProcessName.equals(info.processName)) { return true; } } return false; } }
三、使用方法(仅供参考)
package com.why.project.xiaomipushdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import com.xiaomi.mipush.sdk.MiPushClient; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*=======================================小米推送SDK相关=============================================*/ updateJpushDeviceId(); } /*=======================================小米推送SDK相关=============================================*/ /**更新设备id接口*/ private void updateJpushDeviceId(){ //====小米推送SDK相关==== String regId = MiPushClient.getRegId(MyApplication.getAppContext()); requestDeviceId(regId);//判断是请求接口还是弹出对话框 } //请求接口存储设备id或者token的方法 private void requestDeviceId(String regId) { //首要条件是设备id值或者token值不为空,否则下面的判断没有意义了 //如果没有设置过别名,或者则需要设置别名 //如果服务器上的deviceID值是空值,表明当前用户还没有绑定任何设备,则直接请求接口,不需要弹出对话框; //如果服务器上的deviceID值不为空,并且客户端获取的设备id值和服务器上的deviceID值相同,则不需要弹出对话框,直接请求接口(这个是卸载重新安装的情况) //如果服务器上的deviceid值不为空,并且客户端获取的设备id值和服务器上的deviceID值不同,则需要弹出对话框(这个是换设备的情况) if (!TextUtils.isEmpty(regId)) { //如果已经设置过别名(存储过了设备id值)了,但是当前的别名(设备id值)和服务器上的不一致,则需要重新设置别名(存储设备id值)(这个是其他设备上登录的情况) } //====小米推送SDK相关==== //貌似需要每一次都要设置别名 setAlias(PreferencesUtils.getString(mContext,Globals.USERNAME_KEY)); } // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口,在任何方便的地方调用都可以。 private void setAlias(String alias) { if (TextUtils.isEmpty(alias)) { ToastUtil.showShortToast(getResources().getString(R.string.error_alias_empty));//alias别名不能为空 return; } if (!ExampleUtil.isValidTagAndAlias(alias)) { ToastUtil.showShortToast(getResources().getString(R.string.error_tag_gs_empty));//格式不对 return; } //====小米推送SDK相关==== MiPushClient.setAlias(MyApplication.getAppContext(), alias, null); } }
四、发送消息
五、实现多个通知在通知栏中并存
六、实现打开应用内指定页面的效果
一般由应用客户端自定义即可,但是有可能会想要实现打开应用内指定页面。对应的网页上的设置:
6.1、添加XMPushActivity【一个透明界面,主要用于获取数据,封装数据,传输数据】
package com.why.project.xiaomipushdemo.xiaomipush; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.why.project.xiaomipushdemo.R; import com.xiaomi.mipush.sdk.MiPushMessage; import com.xiaomi.mipush.sdk.PushMessageHelper; import org.json.JSONObject; import cn.jpush.android.api.JPushInterface; /** * Created by HaiyuKing * Used 小米推送【打开应用内指定页面】【暂时用不到】 */ public class XMpushActivity extends Activity { private static final String TAG = XMpushActivity.class.getSimpleName(); private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_xmpush); mContext = this; //获取自定义动作的值 Intent intent = getIntent(); String intentUri = intent.toUri(Intent.URI_INTENT_SCHEME); LogUtil.e(TAG,"action是:" + intentUri); //intent:#Intent;launchFlags=0x10000000;package=com.why.project.xiaomipushdemo;component=com.why.project.xiaomipushdemo/.xiaomipush.XMpushActivity;S.messageId=sdm04994545992668152zH;i.eventMessageType=1000;end /*获取自定义键值对的值*/ MiPushMessage msgContent = (MiPushMessage) intent.getSerializableExtra(PushMessageHelper.KEY_MESSAGE); //关闭当前界面,跳转到指定的界面 try { String title = msgContent.getTitle(); String content = msgContent.getContent(); JSONObject extraJson = new JSONObject(msgContent.getExtra());//将map转成json对象 Bundle bundle = new Bundle(); bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE,title);//通知的标题 bundle.putString(JPushInterface.EXTRA_ALERT,content);//通知内容 bundle.putString(JPushInterface.EXTRA_EXTRA,extraJson.toString());//通知附加字段 bundle.putInt(JPushInterface.EXTRA_NOTIFICATION_ID,msgContent.getNotifyId());//通知id值【没什么用】 Intent i = new Intent(mContext, JpushActivity.class); i.putExtras(bundle); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//必须使用这个,这个保证了多个通知,点击返回返回到的是上一个通知界面 mContext.startActivity(i); finish(); } catch (Exception e){ e.printStackTrace(); } } }
<?xml version="1.0" encoding="utf-8"?> <!-- ======================小米推送SDK====================== --> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.constraint.ConstraintLayout>
6.2、在AndroidManifest.xml中添加以下代码
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.why.project.xiaomipushdemo"> <!-- ======================小米推送SDK====================== --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <!-- the following 2 com.xiaomi.mipushdemo should be changed to your package name --> <permission android:name="${applicationId}.permission.MIPUSH_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="${applicationId}.permission.MIPUSH_RECEIVE" /> <uses-permission android:name="android.permission.VIBRATE" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <!-- ======================小米推送SDK========================== --> <service android:name="com.xiaomi.push.service.XMJobService" android:enabled="true" android:exported="false" android:permission="android.permission.BIND_JOB_SERVICE" android:process=":pushservice" /> <service android:name="com.xiaomi.push.service.XMPushService" android:enabled="true" android:process=":pushservice" /> <service android:name="com.xiaomi.mipush.sdk.PushMessageHandler" android:enabled="true" android:exported="true" /> <service android:name="com.xiaomi.mipush.sdk.MessageHandleService" android:enabled="true" /> <!--自定义一个BroadcastReceiver类:为了接收消息--> <receiver android:name="com.why.project.xiaomipushdemo.xiaomipush.XiaomiMessageReceiver" android:exported="true"> <intent-filter> <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" /> </intent-filter> <intent-filter> <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" /> </intent-filter> <intent-filter> <action android:name="com.xiaomi.mipush.ERROR" /> </intent-filter> </receiver> <receiver android:name="com.xiaomi.push.service.receivers.NetworkStatusReceiver" android:exported="true"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> <receiver android:name="com.xiaomi.push.service.receivers.PingReceiver" android:exported="false" android:process=":pushservice"> <intent-filter> <action android:name="com.xiaomi.push.PING_TIMER" /> </intent-filter> </receiver> <!--小米推送【打开应用内指定页面】【暂时用不到】--> <!--intent:#Intent;component=com.why.project.xiaomipushdemo/.xiaomipush.XMpushActivity;end--> <activity android:name="com.why.project.xiaomipushdemo.xiaomipush.XMpushActivity" android:theme="@android:style/Theme.Translucent"> </activity> </application> </manifest>
6.3、网页发送消息(关键部分)
intent:#Intent;component=com.why.project.xiaomipushdemo/.xiaomipush.XMpushActivity;end
混淆配置
橙色标记的需要换成实际的路径:
#=====================小米推送SDK=====================
#这里com.xiaomi.mipushdemo.DemoMessageRreceiver改成app中定义的完整类名
-keep class com.why.project.xiaomipushdemo.xiaomipush.XiaomiMessageReceiver {*;}
#可以防止一个误报的 warning 导致无法成功编译,如果编译使用的 Android 版本是 23。
-dontwarn com.xiaomi.push.**
参考资料
暂时空缺
项目demo下载地址
链接:https://pan.baidu.com/s/1ClztXBTHIgVgY0vzWwnnFQ 提取码:gne6