Android学习系列(7)--App消息通知机制

时间:2023-03-09 08:03:44
Android学习系列(7)--App消息通知机制
有人说,程序员很安静,但我不完全同意,程序员的聒噪,是藏在代码后面,是藏在程序后面。
这篇文章是Android开发人员的必备知识,是我特别为大家整理和总结的,不求完美,但是有用。
1.消息推送机制
     服务器器端需要变被动为主动,通知客户一些开发商认为重要的信息,无论应用程序是否正在运行或者关闭。
     我想到了一句话:Don't call me,i will call you!
     QQ今天在右下角弹出了一个对话框:"奥巴马宣布本拉登挂了...",正是如此。
     自作聪明,就会带点小聪明,有人喜欢就有人讨厌。
2.独立进程
     无论程序是否正在运行,我们都要能通知到客户,我们需要一个独立进程的后台服务。
     我们需要一个独立进程的后台服务。
     在AndroidManifest.xml中注册Service时,有一个android:process属性,如果这个属性以"."开头,则为此服务开启一个全局的独立进程,如果以":"开头则为此服务开启一个为此应用私有的独立进程。举个具体的例子吧,我们新建了一个 Application,创建了主进程com.cnblogs.tianxia,那么:
  1. <!--下面会创建一个全局的com.cnblogs.tianxia.message的独立进程-->
  2. <service android:name=".service.MessageService" android:label="消息推送" android:process=".message" />
  3. <!--或者-->
  4. <!--下面会创建一个应用私有的com.cnblogs.tianxia:message的独立进程-->
  5. <service android:name=".service.MessageService" android:label="消息推送" android:process=":message" />

复制代码

我们没必要建立一个全局的,本文选择第二种方案,创建一个当前应用私有的独立进程。
3.通知用户和点击查看
  1. public class MessageService extends Service {
  2. //获取消息线程
  3. private MessageThread messageThread = null;
  4. //点击查看
  5. private Intent messageIntent = null;
  6. private PendingIntent messagePendingIntent = null;
  7. //通知栏消息
  8. private int messageNotificationID = 1000;
  9. private Notification messageNotification = null;
  10. private NotificationManager messageNotificatioManager = null;
  11. public IBinder onBind(Intent intent) {
  12. return null;
  13. }
  14. @Override
  15. public int onStartCommand(Intent intent, int flags, int startId) {
  16. //初始化
  17. messageNotification = new Notification();
  18. messageNotification.icon = R.drawable.icon;
  19. messageNotification.tickerText = "新消息";
  20. messageNotification.defaults = Notification.DEFAULT_SOUND;
  21. messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  22. messageIntent = new Intent(this, MessageActivity.class);
  23. messagePendingIntent = PendingIntent.getActivity(this,0,messageIntent,0);
  24. //开启线程
  25. messageThread = new MessageThread();
  26. messageThread.isRunning = true;
  27. messageThread.start();
  28. return super.onStartCommand(intent, flags, startId);
  29. }
  30. /**
  31. * 从服务器端获取消息
  32. *
  33. */
  34. class MessageThread extends Thread{
  35. //运行状态,下一步骤有大用
  36. public boolean isRunning = true;
  37. public void run() {
  38. while(isRunning){
  39. try {
  40. //休息10分钟
  41. Thread.sleep(600000);
  42. //获取服务器消息
  43. String serverMessage = getServerMessage();
  44. if(serverMessage!=null&&!"".equals(serverMessage)){
  45. //更新通知栏
  46. messageNotification.setLatestEventInfo(MessageService.this,"新消息","奥巴马宣布,本拉登兄弟挂了!"+serverMessage,messagePendingIntent);
  47. messageNotificatioManager.notify(messageNotificationID, messageNotification);
  48. //每次通知完,通知ID递增一下,避免消息覆盖掉
  49. messageNotificationID++;
  50. }
  51. } catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }
  56. }
  57. /**
  58. * 这里以此方法为服务器Demo,仅作示例
  59. * @return 返回服务器要推送的消息,否则如果为空的话,不推送
  60. */
  61. public String getServerMessage(){
  62. return "YES!";
  63. }
  64. }

复制代码

其中MessageActivity是点击跳转的activity,负责处理查看详细信息。
  我们在其他Activity中调用一下:

  1. boolean isMessagePush = true;//不开启就设置为false;
  2. ...
  3. if(isMessagePush){
  4. startService(new Intent(this, MessageService.class))
  5. };

复制代码

运行一下:
<ignore_js_op>Android学习系列(7)--App消息通知机制
4.停止服务
  1. stopService(new Intent(MyActivity.this,MessageService.class));
  2. setMessagePush(false);//设置配置文件或数据库中flag为false

复制代码

运行一下,停止服务后,却出乎意料的并没有停下来,怎么回事?是不是代码写错了?
    代码没有错,错在我们停止了服务,却没有停止进程,退出线程。
5.退出线程
    实践证明,Thread的stop()方法并不可靠。但是我们有其他的办法。
    在代码面前,程序员就是上帝。
    退出线程有两种方法。
    第一种方法,强制退出。
  1. //杀死该线程所在的进程,自然就退出了
  2. System.exit(0);

复制代码

第二种方法,设置isRunning为false。

  1. //前面说到了isRunning这个标志,设置为false后,线程的执行就从while循环中跳出来了,然后自然结束掉了
  2. messageThread.isRunning = false;

复制代码

综合一下,我们在MessageService中重载onDestroy()方法如下:

  1. @Override
  2. public void onDestroy() {
  3. System.exit(0);
  4. //或者,二选一,推荐使用System.exit(0),这样进程退出的更干净
  5. //messageThread.isRunning = false;
  6. super.onDestroy();
  7. }

复制代码

好了,现在无论是手动停止,还是从任务管理器中强制停止Service,消息服务和消息线程都能正常的停止和退出了。
   我想我已经清楚了说明了消息推送机制的实现原理,觉得好的话,各位同道,支持一下!

本文作者:谦虚的天下