Android消息推送:手把手教你集成小米推送(附demo)
前言
在android开发中,消息推送功能的使用非常常见。
为了降低开发成本,使用第三方推送是现今较为流行的解决方案。
今天,我将手把手教大家如何在你的应用里集成小米推送
目录
1. 官方demo解析
首先,我们先对小米官方的推送demo进行解析。
请先到官网下载官方demo和sdk说明文档
1.1 demo概况
目录说明:
demoapplication类
继承自application类,其作用主要是:设置app的id & key、注册推送服务
demomessagereceiver类
继承自broadcastreceiver,用于接收推送消息并对这些消息进行处理
mainactivity
实现界面按钮处理 & 设置本地推送方案
timeintervaldialog
设置推送的时间间段
接下来,我将对每个类进行详细分析
1.2 详细分析
1.2.1 demoapplication类
继承自application类,其作用主要是:
- 设置app的id & key
- 注册推送服务
接下来我们通过代码来看下这两个功能如何实现:
demoapplication.java
package com.xiaomi.mipushdemo; import android.app.activitymanager; import android.app.activitymanager.runningappprocessinfo; import android.app.application; import android.content.context; import android.os.handler; import android.os.message; import android.os.process; import android.text.textutils; import android.util.log; import android.widget.toast; import com.xiaomi.channel.commonutils.logger.loggerinterface; import com.xiaomi.mipush.sdk.logger; import com.xiaomi.mipush.sdk.mipushclient; import java.util.list; public class demoapplication extends application { // 使用自己app的id(官网注册的) private static final string app_id = "1000270"; // 使用自己app的key(官网注册的) private static final string app_key = "670100056270"; // 此tag在adb logcat中检索自己所需要的信息, 只需在命令行终端输入 adb logcat | grep // com.xiaomi.mipushdemo public static final string tag = "com.xiaomi.mipushdemo"; private static demohandler shandler = null; private static mainactivity smainactivity = null; //为了提高推送服务的注册率,官方demo建议在application的oncreate中初始化推送服务 //你也可以根据需要,在其他地方初始化推送服务 @override public void oncreate() { super.oncreate(); //判断用户是否已经打开app,详细见下面方法定义 if (shouldinit()) { //注册推送服务 //注册成功后会向demomessagereceiver发送广播 // 可以从demomessagereceiver的oncommandresult方法中mipushcommandmessage对象参数中获取注册信息 mipushclient.registerpush(this, app_id, app_key); //参数说明 //context:android平台上app的上下文,建议传入当前app的application context //appid:在开发者网站上注册时生成的,mipush推送服务颁发给app的唯一认证标识 //appkey:在开发者网站上注册时生成的,与appid相对应,用于验证appid是否合法 } //下面是与测试相关的日志设置 loggerinterface newlogger = new loggerinterface() { @override public void settag(string tag) { // ignore } @override public void log(string content, throwable t) { log.d(tag, content, t); } @override public void log(string content) { log.d(tag, content); } }; logger.setlogger(this, newlogger); if (shandler == null) { shandler = new demohandler(getapplicationcontext()); } } //通过判断手机里的所有进程是否有这个app的进程 //从而判断该app是否有打开 private boolean shouldinit() { //通过activitymanager我们可以获得系统里正在运行的activities //包括进程(process)等、应用程序/包、服务(service)、任务(task)信息。 activitymanager am = ((activitymanager) getsystemservice(context.activity_service)); list<runningappprocessinfo> processinfos = am.getrunningappprocesses(); string mainprocessname = getpackagename(); //获取本app的唯一标识 int mypid = process.mypid(); //利用一个增强for循环取出手机里的所有进程 for (runningappprocessinfo info : processinfos) { //通过比较进程的唯一标识和包名判断进程里是否存在该app if (info.pid == mypid && mainprocessname.equals(info.processname)) { return true; } } return false; } public static demohandler gethandler() { return shandler; } public static void setmainactivity(mainactivity activity) { smainactivity = activity; } //通过设置handler来设置提示文案 public static class demohandler extends handler { private context context; public demohandler(context context) { this.context = context; } @override public void handlemessage(message msg) { string s = (string) msg.obj; if (smainactivity != null) { smainactivity.refreshloginfo(); } if (!textutils.isempty(s)) { toast.maketext(context, s, toast.length_long).show(); } } } }
总结:
步骤1:先判断应用app是否已开启 - 通过判断系统里的进程
通过静态方法
public static void registerpush(context context, string appid, string appkey)
进行推送服务注册,详细参数如下:
为了提高注册率,最好在application的oncreate中初始化推送服务
你也可以根据需要,在其他地方初始化推送服务
1.2.2 demomessagereceiver类
继承自pushmessagereceiver(抽象类,继承自broadcastreceiver),其作用主要是:
- 接收推送消息
- 对推送消息进行处理
demomessagereceiver.java
package com.xiaomi.mipushdemo; import android.annotation.suppresslint; import android.content.context; import android.os.message; import android.text.textutils; import android.util.log; import com.xiaomi.mipush.sdk.errorcode; import com.xiaomi.mipush.sdk.mipushclient; import com.xiaomi.mipush.sdk.mipushcommandmessage; import com.xiaomi.mipush.sdk.mipushmessage; import com.xiaomi.mipush.sdk.pushmessagereceiver; import java.text.simpledateformat; import java.util.date; import java.util.list; /** * 1、pushmessagereceiver 是个抽象类,该类继承了 broadcastreceiver。 * 2、需要将自定义的 demomessagereceiver 注册在 androidmanifest.xml public class demomessagereceiver extends pushmessagereceiver { private string mregid; private string mtopic; private string malias; private string maccount; private string mstarttime; private string mendtime; //透传消息到达客户端时调用 //作用:可通过参数message从而获得透传消息,具体请看官方sdk文档 @override public void onreceivepassthroughmessage(context context, mipushmessage message) { log.v(demoapplication.tag, "onreceivepassthroughmessage is called. " + message.tostring()); string log = context.getstring(r.string.recv_passthrough_message, message.getcontent()); mainactivity.loglist.add(0, getsimpledate() + " " + log); if (!textutils.isempty(message.gettopic())) { mtopic = message.gettopic(); } else if (!textutils.isempty(message.getalias())) { malias = message.getalias(); } message msg = message.obtain(); msg.obj = log; demoapplication.gethandler().sendmessage(msg); } //通知消息到达客户端时调用 //注:应用在前台时不弹出通知的通知消息到达客户端时也会回调函数 //作用:通过参数message从而获得通知消息,具体请看官方sdk文档 @override public void onnotificationmessagearrived(context context, mipushmessage message) { log.v(demoapplication.tag, "onnotificationmessagearrived is called. " + message.tostring()); string log = context.getstring(r.string.arrive_notification_message, message.getcontent()); mainactivity.loglist.add(0, getsimpledate() + " " + log); if (!textutils.isempty(message.gettopic())) { mtopic = message.gettopic(); } else if (!textutils.isempty(message.getalias())) { malias = message.getalias(); } message msg = message.obtain(); msg.obj = log; demoapplication.gethandler().sendmessage(msg); } //用户手动点击通知栏消息时调用 //注:应用在前台时不弹出通知的通知消息到达客户端时也会回调函数 //作用:1. 通过参数message从而获得通知消息,具体请看官方sdk文档 //2. 设置用户点击消息后打开应用 or 网页 or 其他页面 @override public void onnotificationmessageclicked(context context, mipushmessage message) { log.v(demoapplication.tag, "onnotificationmessageclicked is called. " + message.tostring()); string log = context.getstring(r.string.click_notification_message, message.getcontent()); mainactivity.loglist.add(0, getsimpledate() + " " + log); if (!textutils.isempty(message.gettopic())) { mtopic = message.gettopic(); } else if (!textutils.isempty(message.getalias())) { malias = message.getalias(); } message msg = message.obtain(); if (message.isnotified()) { msg.obj = log; } demoapplication.gethandler().sendmessage(msg); } //用来接收客户端向服务器发送命令后的响应结果。 @override public void oncommandresult(context context, mipushcommandmessage message) { log.v(demoapplication.tag, "oncommandresult is called. " + message.tostring()); string command = message.getcommand(); list<string> arguments = message.getcommandarguments(); string cmdarg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null); string cmdarg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null); string log; if (mipushclient.command_register.equals(command)) { if (message.getresultcode() == errorcode.success) { mregid = cmdarg1; log = context.getstring(r.string.register_success); } else { log = context.getstring(r.string.register_fail); } } else if (mipushclient.command_set_alias.equals(command)) { if (message.getresultcode() == errorcode.success) { malias = cmdarg1; log = context.getstring(r.string.set_alias_success, malias); } else { log = context.getstring(r.string.set_alias_fail, message.getreason()); } } else if (mipushclient.command_unset_alias.equals(command)) { if (message.getresultcode() == errorcode.success) { malias = cmdarg1; log = context.getstring(r.string.unset_alias_success, malias); } else { log = context.getstring(r.string.unset_alias_fail, message.getreason()); } } else if (mipushclient.command_set_account.equals(command)) { if (message.getresultcode() == errorcode.success) { maccount = cmdarg1; log = context.getstring(r.string.set_account_success, maccount); } else { log = context.getstring(r.string.set_account_fail, message.getreason()); } } else if (mipushclient.command_unset_account.equals(command)) { if (message.getresultcode() == errorcode.success) { maccount = cmdarg1; log = context.getstring(r.string.unset_account_success, maccount); } else { log = context.getstring(r.string.unset_account_fail, message.getreason()); } } else if (mipushclient.command_subscribe_topic.equals(command)) { if (message.getresultcode() == errorcode.success) { mtopic = cmdarg1; log = context.getstring(r.string.subscribe_topic_success, mtopic); } else { log = context.getstring(r.string.subscribe_topic_fail, message.getreason()); } } else if (mipushclient.command_unsubscribe_topic.equals(command)) { if (message.getresultcode() == errorcode.success) { mtopic = cmdarg1; log = context.getstring(r.string.unsubscribe_topic_success, mtopic); } else { log = context.getstring(r.string.unsubscribe_topic_fail, message.getreason()); } } else if (mipushclient.command_set_accept_time.equals(command)) { if (message.getresultcode() == errorcode.success) { mstarttime = cmdarg1; mendtime = cmdarg2; log = context.getstring(r.string.set_accept_time_success, mstarttime, mendtime); } else { log = context.getstring(r.string.set_accept_time_fail, message.getreason()); } } else { log = message.getreason(); } mainactivity.loglist.add(0, getsimpledate() + " " + log); message msg = message.obtain(); msg.obj = log; demoapplication.gethandler().sendmessage(msg); } //用于接收客户端向服务器发送注册命令后的响应结果。 @override public void onreceiveregisterresult(context context, mipushcommandmessage message) { log.v(demoapplication.tag, "onreceiveregisterresult is called. " + message.tostring()); string command = message.getcommand(); list<string> arguments = message.getcommandarguments(); string cmdarg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null); string log; if (mipushclient.command_register.equals(command)) { if (message.getresultcode() == errorcode.success) { mregid = cmdarg1; //打印日志:注册成功 log = context.getstring(r.string.register_success); } else { //打印日志:注册失败 log = context.getstring(r.string.register_fail); } } else { log = message.getreason(); } message msg = message.obtain(); msg.obj = log; demoapplication.gethandler().sendmessage(msg); } @suppresslint("simpledateformat") private static string getsimpledate() { return new simpledateformat("mm-dd hh:mm:ss").format(new date()); } }
总结
根据需要复写pushmessagereceiver里对消息的相关处理方法,以下是相关方法的详情:
关于oncommandresult(context context,mipushcommandmessage message)
a. 作用:当客户端向服务器发送注册push、设置alias、取消注册alias、订阅topic、取消订阅topic等等命令后,从服务器返回结果。
b. 参数说明:
1.2.3 mainactivity
用于给用户设置标识,如别名、标签、账号等等
mainactivity.java
public class mainactivity extends activity { public static list<string> loglist = new copyonwritearraylist<string>(); private textview mlogview = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); demoapplication.setmainactivity(this); mlogview = (textview) findviewbyid(r.id.log); // 设置别名 findviewbyid(r.id.set_alias).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.set_alias) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string alias = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.setalias(mainactivity.this, alias, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 撤销别名 findviewbyid(r.id.unset_alias).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.unset_alias) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string alias = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.unsetalias(mainactivity.this, alias, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 设置帐号 findviewbyid(r.id.set_account).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.set_account) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string account = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.setuseraccount(mainactivity.this, account, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 撤销帐号 findviewbyid(r.id.unset_account).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.unset_account) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string account = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.unsetuseraccount(mainactivity.this, account, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 设置标签 findviewbyid(r.id.subscribe_topic).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.subscribe_topic) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string topic = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.subscribe(mainactivity.this, topic, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 撤销标签 findviewbyid(r.id.unsubscribe_topic).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final edittext edittext = new edittext(mainactivity.this); new alertdialog.builder(mainactivity.this) .settitle(r.string.unsubscribe_topic) .setview(edittext) .setpositivebutton(r.string.ok, new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { string topic = edittext.gettext().tostring(); //调用静态方法进行设置 mipushclient.unsubscribe(mainactivity.this, topic, null); } }) .setnegativebutton(r.string.cancel, null) .show(); } }); // 设置接收消息时间 findviewbyid(r.id.set_accept_time).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { new timeintervaldialog(mainactivity.this, new timeintervalinterface() { @override public void apply(int starthour, int startmin, int endhour, int endmin) { //调用静态方法进行设置 mipushclient.setaccepttime(mainactivity.this, starthour, startmin, endhour, endmin, null); } @override public void cancel() { //ignore } }) .show(); } }); // 暂停推送 findviewbyid(r.id.pause_push).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { mipushclient.pausepush(mainactivity.this, null); } }); findviewbyid(r.id.resume_push).setonclicklistener(new onclicklistener() { @override public void onclick(view v) { //调用静态方法进行设置 mipushclient.resumepush(mainactivity.this, null); } }); } @override protected void onresume() { super.onresume(); refreshloginfo(); } @override protected void ondestroy() { super.ondestroy(); demoapplication.setmainactivity(null); } public void refreshloginfo() { string alllog = ""; for (string log : loglist) { alllog = alllog + log + "\n\n"; } mlogview.settext(alllog); } }
总结:
根据需求对不同用户设置不同的推送标识,如别名、标签等等。
a. 别名(alias)
1、开发者可以为指定用户设置别名,然后给这个别名推送消息,
效果等同于给regid推送消息,alias是除regid(自动生成的)和useraccount之外的第三个用户标识
2、开发者可以取消指定用户的某个别名,服务器就不会给这个别名推送消息了。
//设置别名 mipushclient.setalias(context context, string alias, string category); //撤销别名 mipushclient.unsetalias(context context, string alias, string category); //参数说明 //context:android平台上app的上下文,建议传入当前app的application context //alias:为指定用户设置别名 / 为指定用户取消别名 //category:扩展参数,暂时没有用途,直接填null //获取该客户端所有的别名 public static list<string> getallalias(final context context)
b. 用户账号(useraccoun)
- 开发者可以为指定用户设置useraccount
- 开发者可以取消指定用户的某个useraccount,服务器就不会给这个useraccount推送消息了
//设置 mipushclient.setuseraccount(final context context, final string useraccount, string category) //撤销 mipushclient.unsetuseraccount(final context context, final string useraccount, string category) //参数说明 //context:android平台上app的上下文,建议传入当前app的application context //useraccount:为指定用户设置useraccount / 为指定用户取消useraccount //category:扩展参数,暂时没有用途,直接填null //获取该客户端所有设置的账号 public static list<string> getalluseraccount(final context context)
c. 标签(topic)
- 开发者可以结合自己的业务特征,给用户打上不同的标签。
- 消息推送时,开发者可以结合每条消息的内容和目标用户,为每条消息选择对应的标签,为开发者可以根据订阅的主题实现分组群发,从而进行消息的精准推送
//设置标签 mipushclient.subscribe(context context, string topic, string category); //撤销标签 mipushclient.unsubscribe(context context, string topic, string category); //参数说明 //context:android平台上app的上下文,建议传入当前app的application context //topic:为指定用户设置设置订阅的主题 / 为指定用户取消订阅的主题 //category:扩展参数,暂时没有用途,直接填null //获取该客户端所有的标签 public static list<string> getalltopic(final context context);
timeintervaldialog
作用:用于设置推送的时间-开始时间+暂停时间
package com.xiaomi.mipushdemo; import android.app.dialog; import android.content.context; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.timepicker; import android.widget.timepicker.ontimechangedlistener; //继承ontimechangedlistener接口 public class timeintervaldialog extends dialog implements ontimechangedlistener { private timeintervalinterface mtimeintervalinterface; private context mcontext; private timepicker mstarttimepicker, mendtimepicker; private int mstarthour, mstartminute, mendhour, mendminute; private button.onclicklistener clicklistener = new button.onclicklistener() { @override public void onclick(view v) { switch (v.getid()) { case r.id.apply: dismiss(); //设置时间参数 mtimeintervalinterface.apply(mstarthour, mstartminute, mendhour, mendminute); break; case r.id.cancel: dismiss(); mtimeintervalinterface.cancel(); break; default: break; } } }; public timeintervaldialog(context context, timeintervalinterface timeintervalinterface, int starthour, int startminute, int endhour, int endminute) { super(context); mcontext = context; this.mtimeintervalinterface = timeintervalinterface; this.mstarthour = starthour; this.mstartminute = startminute; this.mendhour = endhour; this.mendminute = endminute; } public timeintervaldialog(context context, timeintervalinterface timeintervalinterface) { this(context, timeintervalinterface, 0, 0, 23, 59); } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.set_time_dialog); setcancelable(true); settitle(mcontext.getstring(r.string.set_accept_time)); mstarttimepicker = (timepicker) findviewbyid(r.id.starttimepicker); mstarttimepicker.setis24hourview(true); mstarttimepicker.setcurrenthour(mstarthour); mstarttimepicker.setcurrentminute(mstartminute); mstarttimepicker.setontimechangedlistener(this); mendtimepicker = (timepicker) findviewbyid(r.id.endtimepicker); mendtimepicker.setis24hourview(true); mendtimepicker.setcurrenthour(mendhour); mendtimepicker.setcurrentminute(mendminute); mendtimepicker.setontimechangedlistener(this); button applybtn = (button) findviewbyid(r.id.apply); applybtn.setonclicklistener(clicklistener); button cancelbtn = (button) findviewbyid(r.id.cancel); cancelbtn.setonclicklistener(clicklistener); } @override public void ontimechanged(timepicker view, int hourofday, int minute) { if (view == mstarttimepicker) { mstarthour = hourofday; mstartminute = minute; } else if (view == mendtimepicker) { mendhour = hourofday; mendminute = minute; } } interface timeintervalinterface { void apply(int starthour, int startmin, int endhour, int endmin); void cancel(); } }
总结
- 使用一个继承了dialog类的timeintervaldialog类进行推送时间的配置
- 可进行的配置:设置推送时间(开始 & 结束)、暂停推送时间、恢复推送时间
//设置推送时间(开始 & 结束) mipushclient.setaccepttime(context context, int starthour, int startmin, int endhour, int endmin, string category) //设置暂停推送时间、恢复推送时间 pausepush(context context, string category)`和`resumepush(context context, string category) //参数说明 //context:android平台上app的上下文,建议传入当前app的application context //starthour:接收时段开始时间的小时 //startmin :接收时段开始时间的分钟 //endhour:接收时段结束时间的小时 //endmin:接收时段结束时间的分钟 //category:扩展参数,暂时没有用途,直接填null
androidmanifest文件的配置
//小米推送支持最低的android版本是2.2 <uses-sdk android:minsdkversion="8"/> //设置一系列权限 <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" /> <uses-permission android:name="android.permission.vibrate" /> //这里com.xiaomi.mipushdemo改成自身app的包名 <permission android:name="com.xiaomi.mipushdemo.permission.mipush_receive" android:protectionlevel="signature" /> //这里com.xiaomi.mipushdemo改成自身app的包名 <uses-permission android:name="com.xiaomi.mipushdemo.permission.mipush_receive" /> //注册广播broadcastreceiver & service //都是静态注册,因为要长期处在后台运行 //注:共是3个广播接收器和4个服务,其中包括继承了pushmessagereceiver的demomessagereceiver //4个后台服务 <service android:enabled="true" android:process=":pushservice" android:name="com.xiaomi.push.service.xmpushservice"/> //此service必须在3.0.1版本以后(包括3.0.1版本)加入 <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必须在2.2.5版本以后(包括2.2.5版本)加入 <service android:enabled="true" android:exported="true" android:name="com.xiaomi.mipush.sdk.pushmessagehandler" /> <service android:enabled="true" android:name="com.xiaomi.mipush.sdk.messagehandleservice" /> //3个广播 <receiver android:exported="true" android:name="com.xiaomi.push.service.receivers.networkstatusreceiver" > <intent-filter> <action android:name="android.net.conn.connectivity_change" /> <category android:name="android.intent.category.default" /> </intent-filter> </receiver> <receiver android:exported="false" android:process=":pushservice" android:name="com.xiaomi.push.service.receivers.pingreceiver" > <intent-filter> <action android:name="com.xiaomi.push.ping_timer" /> </intent-filter> </receiver> //继承了pushmessagereceiver的demomessagereceiver的广播注册 <receiver android:name="com.xiaomi.mipushdemo.demomessagereceiver" 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>
2. 集成小米推送步骤汇总
- 步骤1:在小米推送平台进行相关注册开发者账号,并进行应用的注册:应用包名,appid和appkey
- 步骤2:将小米推送的sdk包加入库
- 步骤3:在应用内初始化小米推送服务
- 步骤4:继承pushmessagereceiver,并复写相关推送消息的方法
- 步骤5:在androidmanifest文件里面配置好权限、注册service和broadcastreceiver
- 在android6.0里面的权限需要动态获取
- 步骤6:根据需要设置一系列的推送设置,如用户别名、标签等等
接下来,我们来按照上面的步骤,一步步来实现一个简易的小米推送demo
3. 实例解析
步骤1:在小米推送平台进行相关注册开发者账号,并进行应用的注册:应用包名,appid和appkey
注意,填入的包名要跟你的应用app的包名是一致的
步骤2:将小米推送的sdk包加入到你应用的库里
步骤3:在应用内初始化小米推送服务
为了提高推送服务的注册率,我选择在application的oncreate中初始化推送服务 *baseactivity.java*
package scut.carson_ho.demo_mipush; 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 carson_ho on 16/10/26. */ //主要要继承application public class baseactivity extends application { // 使用自己app的id(官网注册的) private static final string app_id = "2882303761517520369"; // 使用自己app的key(官网注册的) private static final string app_key = "5401752085369"; //为了提高推送服务的注册率,我建议在application的oncreate中初始化推送服务 //你也可以根据需要,在其他地方初始化推送服务 @override public void oncreate() { super.oncreate(); if (shouldinit()) { //注册推送服务 //注册成功后会向demomessagereceiver发送广播 // 可以从demomessagereceiver的oncommandresult方法中mipushcommandmessage对象参数中获取注册信息 mipushclient.registerpush(this, app_id, app_key); } } //通过判断手机里的所有进程是否有这个app的进程 //从而判断该app是否有打开 private boolean shouldinit() { //通过activitymanager我们可以获得系统里正在运行的activities //包括进程(process)等、应用程序/包、服务(service)、任务(task)信息。 activitymanager am = ((activitymanager) getsystemservice(context.activity_service)); list<activitymanager.runningappprocessinfo> processinfos = am.getrunningappprocesses(); string mainprocessname = getpackagename(); //获取本app的唯一标识 int mypid = process.mypid(); //利用一个增强for循环取出手机里的所有进程 for (activitymanager.runningappprocessinfo info : processinfos) { //通过比较进程的唯一标识和包名判断进程里是否存在该app if (info.pid == mypid && mainprocessname.equals(info.processname)) { return true; } } return false; } }
注意要在android.manifest.xml里的application里加入
android:name=".baseactivity"
这样在应用初始化时是第一个加载baseactivity.java类文件的
如下图:
步骤4:设置子类继承pushmessagereceiver,并复写相关推送消息的方法
mipush_broadcast.java
package scut.carson_ho.demo_mipush; import android.content.context; import com.xiaomi.mipush.sdk.errorcode; import com.xiaomi.mipush.sdk.mipushclient; import com.xiaomi.mipush.sdk.mipushcommandmessage; import com.xiaomi.mipush.sdk.mipushmessage; import com.xiaomi.mipush.sdk.pushmessagereceiver; /** * created by carson_ho on 16/10/26. */ public class mipush_broadcast extends pushmessagereceiver { //透传消息到达客户端时调用 //作用:可通过参数message从而获得透传消息,具体请看官方sdk文档 @override public void onreceivepassthroughmessage(context context, mipushmessage message) { //打印消息方便测试 system.out.println("透传消息到达了"); system.out.println("透传消息是"+message.tostring()); } //通知消息到达客户端时调用 //注:应用在前台时不弹出通知的通知消息到达客户端时也会回调函数 //作用:通过参数message从而获得通知消息,具体请看官方sdk文档 @override public void onnotificationmessagearrived(context context, mipushmessage message) { //打印消息方便测试 system.out.println("通知消息到达了"); system.out.println("通知消息是"+message.tostring()); } //用户手动点击通知栏消息时调用 //注:应用在前台时不弹出通知的通知消息到达客户端时也会回调函数 //作用:1. 通过参数message从而获得通知消息,具体请看官方sdk文档 //2. 设置用户点击消息后打开应用 or 网页 or 其他页面 @override public void onnotificationmessageclicked(context context, mipushmessage message) { //打印消息方便测试 system.out.println("用户点击了通知消息"); system.out.println("通知消息是" + message.tostring()); system.out.println("点击后,会进入应用" ); } //用来接收客户端向服务器发送命令后的响应结果。 @override public void oncommandresult(context context, mipushcommandmessage message) { string command = message.getcommand(); system.out.println(command ); if (mipushclient.command_register.equals(command)) { if (message.getresultcode() == errorcode.success) { //打印信息便于测试注册成功与否 system.out.println("注册成功"); } else { system.out.println("注册失败"); } } } //用于接收客户端向服务器发送注册命令后的响应结果。 @override public void onreceiveregisterresult(context context, mipushcommandmessage message) { string command = message.getcommand(); system.out.println(command ); if (mipushclient.command_register.equals(command)) { if (message.getresultcode() == errorcode.success) { //打印日志:注册成功 system.out.println("注册成功"); } else { //打印日志:注册失败 system.out.println("注册失败"); } } else { system.out.println("其他情况"+message.getreason()); } } }
步骤5:在androidmanifest文件里面配置好权限、注册service和broadcastreceiver
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="scut.carson_ho.demo_mipush"> //相关权限 <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" /> <uses-permission android:name="android.permission.vibrate" /> //注意这里.permission.mipush_receive是自身app的包名 <permission android:name="scut.carson_ho.demo_mipush.permission.mipush_receive" android:protectionlevel="signature" /> //注意这里.permission.mipush_receive是自身app的包名 <uses-permission android:name="scut.carson_ho.demo_mipush.permission.mipush_receive" /> //注意要初始化baseactivity.java类 <application android:name=".baseactivity" android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" 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> //注册广播broadcastreceiver和service //都是静态注册,因为要长期处在后台运行 //注:共是3个广播接收器和4个服务,其中包括继承了pushmessagereceiver的demomessagereceiver //4个后台服务 <service android:enabled="true" android:process=":pushservice" android:name="com.xiaomi.push.service.xmpushservice"/> //此service必须在3.0.1版本以后(包括3.0.1版本)加入 <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必须在2.2.5版本以后(包括2.2.5版本)加入 <service android:enabled="true" android:exported="true" android:name="com.xiaomi.mipush.sdk.pushmessagehandler" /> <service android:enabled="true" android:name="com.xiaomi.mipush.sdk.messagehandleservice" /> //3个广播 <receiver android:exported="true" android:name="com.xiaomi.push.service.receivers.networkstatusreceiver" > <intent-filter> <action android:name="android.net.conn.connectivity_change" /> <category android:name="android.intent.category.default" /> </intent-filter> </receiver> <receiver android:exported="false" android:process=":pushservice" android:name="com.xiaomi.push.service.receivers.pingreceiver" > <intent-filter> <action android:name="com.xiaomi.push.ping_timer" /> </intent-filter> </receiver> //继承了pushmessagereceiver的demomessagereceiver的广播注册 <receiver android:name=".mipush_broadcast" 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> </application> </manifest>
步骤6:根据需要设置一系列的推送设置,如用户别名、标签等等
- 此处是简单demo,所以不作过多的设置
- 更多设置请回看上方官方demo解析
运行结果
好了,客户端的代码写好后,可以去小米官网测试一下消息推送了
步骤1:在小米官网的消息推送里选择你创建的应用,然后点击“推送工具”
步骤2:设置推送消息的相关信息
可进行的配置非常全面,基本上能满足推送的需求
推送的结果
4. demo下载地址 demo
5. 关于对小米推送的思考(问题)
上述说的小米推送看似简单:初始化推送服务 + 相关推送设置。但是,好的代码不仅能在正常情况下工作,还应该充分考虑失败情况。那么,有什么样的失败情况需要我们考虑呢?
- 背景:在这个初始化推送服务的过程中,是需要联系小米推送的服务器来申请reg id(即推送token)。
- 冲突:初始化过程可能失败:网络问题(没网or网络信号弱)、服务器问题导致初始化失败。那么,当失败以后,该什么时候再次进行初始化呢?
- 解决方案:在初始化失败的情况下提供重试机制,直到初始化成功(可以通过检测是否已经拿到推送token来确定),问题解决的逻辑如下:
总结
全面考虑到所有异常问题并恰当地进行处理才能真正体现程序猿的功力,希望大家做撸代码的时候不要只做代码的搬运工,纯粹写代码并不会让你成长,关键在于思考。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。