版權聲明:本文爲HaiyuKing原創文章,轉載請註明出處!java
這個Demo只是記錄小米推送的集成,不能運行。android
注意事項:json
一、 導入類文件後須要change包名以及從新import R文件路徑api
二、 Values目錄下的文件(strings.xml、dimens.xml、colors.xml等),若是項目中存在,則複製裏面的內容,不要整個覆蓋服務器
參考官網《小米推送服務啓用指南》app
註冊小米開發者帳號——》啓用推送ide
下載地址:http://admin.xmpush.xiaomi.com/mipush/downpage/gradle
下載後的壓縮包解壓後的目錄:ui
爲了便於管理,我在Demo中新建了一個ThirdLib的module,用於集成SDK。this
//引用thirdlib
implementation project(':thirdlib')
複製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')
<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>
注意下面標記橙色代碼:
<?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>
一、PermissionActivity中須要用到自定義MyApplication中的代碼,下一步中會增長,這裏報錯不用管;
二、XiaomiMessageReceiver中使用的到字符串資源在thirdLib中的res/strings.xml文件中定義了;
三、XiaomiMessageReceiver主要通知、消息的回調
在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); } }
通常由應用客戶端自定義便可,可是有可能會想要實現打開應用內指定頁面。對應的網頁上的設置:
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>
<?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>
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.**
暫時空缺
連接:https://pan.baidu.com/s/1ClztXBTHIgVgY0vzWwnnFQ 提取碼:gne6