当前位置:   article > 正文

Android中的Service模板,通过Service发送通知并修改通知的提示音_android 在service中创建消息通知

android 在service中创建消息通知

         Sercvice作为android中的四大组件之一,主要用来执行后台耗时任务,比如上传大文件、轮询服务器消息、间断向服务器发送数据、应用处于后台运行时向用户推送通知等等,使用场景多样,但是Service跟Activity一样,也有它的代码模板,这里给出通过StartService启动发送通知的方式的Service代码模板,便于快速开发。

       通知已经适配了android8.0版本,这里顺便提一下由于通知在8.0版本android源码改动比较大,提出了一种channel的方式来管理通知,所以当项目的targetVersion>=26的时候需要做版本适配,并手动在设置的通知管理中心内打开通道,才能看到效果,channel通道默认是关闭的。

这里就直接贴上代码了:

  1. public class MessgeService extends Service {
  2. private static final Class[] mStartForegroundSignature = new Class[]{
  3. int.class, Notification.class};
  4. private static final Class[] mStopForegroundSignature = new Class[]{boolean.class};
  5. private NotificationManager mNM;
  6. private Method mStartForeground;
  7. private Method mStopForeground;
  8. private Object[] mStartForegroundArgs = new Object[2];
  9. private Object[] mStopForegroundArgs = new Object[1];
  10. private Uri sound;
  11. private Uri soundDefault;
  12. @Override
  13. public IBinder onBind(Intent intent) {
  14. return null;
  15. }
  16. @Override
  17. public void onCreate() {
  18. super.onCreate();
  19. mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  20. sound = Uri.parse("android.resource://" + getPackageName() + "/raw/alarm_voice");
  21. try {
  22. mStartForeground = MessgeService.class.getMethod("startForeground",
  23. mStartForegroundSignature);
  24. mStopForeground = MessgeService.class.getMethod("stopForeground",
  25. mStopForegroundSignature);
  26. } catch (NoSuchMethodException e) {
  27. mStartForeground = mStopForeground = null;
  28. }
  29. // 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT,因为
  30. // 前台服务的 notification.flags 总是默认包含了那个标志位
  31. Notification notification = new Notification();
  32. // 注意使用 startForeground ,id 为 0 将不会显示 notification,1显示
  33. startForegroundCompat(0, notification);
  34. new Thread(r).start();
  35. }
  36. private Runnable r = new Runnable() {
  37. @Override
  38. public void run() {
  39. while (true) {
  40. handler.sendEmptyMessage(0);
  41. try {
  42. Thread.sleep(30000);
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48. };
  49. @Override
  50. public void onDestroy() {
  51. super.onDestroy();
  52. stopForegroundCompat(1);
  53. }
  54. // 以兼容性方式开始前台服务
  55. private void startForegroundCompat(int id, Notification n) {
  56. if (mStartForeground != null) {
  57. mStartForegroundArgs[0] = id;
  58. mStartForegroundArgs[1] = n;
  59. try {
  60. mStartForeground.invoke(this, mStartForegroundArgs);
  61. } catch (IllegalArgumentException e) {
  62. e.printStackTrace();
  63. } catch (IllegalAccessException e) {
  64. e.printStackTrace();
  65. } catch (InvocationTargetException e) {
  66. e.printStackTrace();
  67. }
  68. return;
  69. }
  70. mNM.notify(id, n);
  71. }
  72. // 以兼容性方式停止前台服务
  73. private void stopForegroundCompat(int id) {
  74. if (mStopForeground != null) {
  75. mStopForegroundArgs[0] = Boolean.TRUE;
  76. try {
  77. mStopForeground.invoke(this, mStopForegroundArgs);
  78. } catch (IllegalArgumentException e) {
  79. e.printStackTrace();
  80. } catch (IllegalAccessException e) {
  81. e.printStackTrace();
  82. } catch (InvocationTargetException e) {
  83. e.printStackTrace();
  84. }
  85. return;
  86. }
  87. // 在 setForeground 之前调用 cancel,因为我们有可能在取消前台服务之后
  88. // 的那一瞬间被kill掉。这个时候 notification 便永远不会从通知一栏移除
  89. mNM.cancel(id);
  90. }
  91. Handler handler = new Handler() {
  92. @Override
  93. public void handleMessage(Message msg) {
  94. super.handleMessage(msg);
  95. getUnreadMessage();
  96. }
  97. };
  98. /**
  99. * 读取未读消息的数量.
  100. */
  101. private void getUnreadMessage() {
  102. new OkHttpClientManager()
  103. .setUrl(MethodConstants.Messge.UNREAD_MESSAGE)
  104. .setOnNetWorkReponse(onNetworkResponse)
  105. .setIngnore(false)
  106. .builder();
  107. }
  108. OkHttpClientManager.OnNetworkResponse onNetworkResponse = new OkHttpClientManager.OnNetworkResponse() {
  109. @Override
  110. public void onNetworkResponse(String result) {
  111. try {
  112. JSONObject json = new JSONObject(result);
  113. int messgeCount = json.optInt("unreadMessageCount");
  114. AppApplication.messgeCount = messgeCount;
  115. AppApplication.getInstance().setSport();
  116. String unreadMessage = json.optString("unreadMessage");
  117. if (!TextUtils.isEmpty(unreadMessage) && !"null".equals(unreadMessage)) {
  118. List<MessgeEntity> list = GsonUtil.stringToList(unreadMessage, MessgeEntity.class);
  119. for (int i = 0; i < list.size() && i < 2; i++) {
  120. String taskMessageType = list.get(i).getTaskMessageType();
  121. if (TextUtils.isEmpty(taskMessageType)) {
  122. showNotifictionIcon(getApplication(), list.get(i), "com.haocang.messge.ui2.MessgeTabLayouFragment", false, null, null);
  123. }
  124. }
  125. }
  126. } catch (JSONException e) {
  127. e.printStackTrace();
  128. }
  129. }
  130. @Override
  131. public void onErrorResponse(Response errorCode) {
  132. }
  133. };
  134. public void showNotifictionIcon(Context context, MessgeEntity entity, String fragmentName, boolean toTaskPage, String type, String taskName) {
  135. Class clazz = null;
  136. try {
  137. clazz = Class.forName("com.haocang.base.ui.CommonActivity");
  138. } catch (ClassNotFoundException e) {
  139. e.printStackTrace();
  140. }
  141. if (clazz != null) {
  142. Intent intent = new Intent(getApplication(), clazz);//点击之后进入MainActivity
  143. intent.putExtra("fragmentName", fragmentName);
  144. intent.putExtra("messageId", entity.getId());
  145. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  146. PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) entity.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);//第二个参数如果id相同会覆盖之前的所有intent
  147. NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  148. String id = "channel_2";//删了会报错 。。。。。
  149. String id_normal= "channel_1";
  150. String name = "aaa";
  151. notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  152. Notification notification;
  153. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  154. String channel_id_actural=id_normal;
  155. if (entity.getMessageCategory() == 2) {
  156. channel_id_actural=id;
  157. }else {
  158. channel_id_actural=id_normal;
  159. }
  160. NotificationChannel mChannel = new NotificationChannel(channel_id_actural, name, NotificationManager.IMPORTANCE_LOW);
  161. if(entity.getMessageCategory() == 2){
  162. mChannel.setSound(sound, Notification.AUDIO_ATTRIBUTES_DEFAULT);
  163. }
  164. notificationManager.createNotificationChannel(mChannel);
  165. notification = new Notification.Builder(this)
  166. .setChannelId(channel_id_actural)
  167. .setContentTitle(entity.getTitle())
  168. .setContentText(entity.getContent())
  169. .setContentIntent(pendingIntent)
  170. .setSmallIcon(R.mipmap.ic_mango).build();
  171. } else {
  172. NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
  173. .setContentTitle(entity.getTitle())
  174. .setContentText(entity.getContent())
  175. .setSmallIcon(R.mipmap.ic_mango)
  176. .setContentIntent(pendingIntent)
  177. // .setDefaults(Notification.DEFAULT_SOUND)
  178. .setOngoing(false);
  179. // .setChannel(id);//无效
  180. if (entity.getMessageCategory() == 2) {
  181. notificationBuilder.setSound(sound, 5);
  182. } else {
  183. notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
  184. }
  185. notification = notificationBuilder.build();
  186. }
  187. notificationManager.notify((int) entity.getId(), notification);
  188. }
  189. }
  190. }

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号