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

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

这里就直接贴上代码了:

public class MessgeService extends Service {private static final Class[] mStartForegroundSignature = new Class[]{int.class, Notification.class};private static final Class[] mStopForegroundSignature = new Class[]{boolean.class};private NotificationManager mNM;private Method mStartForeground;private Method mStopForeground;private Object[] mStartForegroundArgs = new Object[2];private Object[] mStopForegroundArgs = new Object[1];private Uri sound;private Uri soundDefault;@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);sound = Uri.parse("android.resource://" + getPackageName() + "/raw/alarm_voice");try {mStartForeground = MessgeService.class.getMethod("startForeground",mStartForegroundSignature);mStopForeground = MessgeService.class.getMethod("stopForeground",mStopForegroundSignature);} catch (NoSuchMethodException e) {mStartForeground = mStopForeground = null;}// 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT,因为// 前台服务的 notification.flags 总是默认包含了那个标志位Notification notification = new Notification();// 注意使用 startForeground ,id 为 0 将不会显示 notification,1显示startForegroundCompat(0, notification);new Thread(r).start();}private Runnable r = new Runnable() {@Overridepublic void run() {while (true) {handler.sendEmptyMessage(0);try {Thread.sleep(30000);} catch (InterruptedException e) {e.printStackTrace();}}}};@Overridepublic void onDestroy() {super.onDestroy();stopForegroundCompat(1);}// 以兼容性方式开始前台服务private void startForegroundCompat(int id, Notification n) {if (mStartForeground != null) {mStartForegroundArgs[0] = id;mStartForegroundArgs[1] = n;try {mStartForeground.invoke(this, mStartForegroundArgs);} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}return;}mNM.notify(id, n);}// 以兼容性方式停止前台服务private void stopForegroundCompat(int id) {if (mStopForeground != null) {mStopForegroundArgs[0] = Boolean.TRUE;try {mStopForeground.invoke(this, mStopForegroundArgs);} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}return;}// 在 setForeground 之前调用 cancel,因为我们有可能在取消前台服务之后// 的那一瞬间被kill掉。这个时候 notification 便永远不会从通知一栏移除mNM.cancel(id);}Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);getUnreadMessage();}};/*** 读取未读消息的数量.*/private void getUnreadMessage() {new OkHttpClientManager().setUrl(MethodConstants.Messge.UNREAD_MESSAGE).setOnNetWorkReponse(onNetworkResponse).setIngnore(false).builder();}OkHttpClientManager.OnNetworkResponse onNetworkResponse = new OkHttpClientManager.OnNetworkResponse() {@Overridepublic void onNetworkResponse(String result) {try {JSONObject json = new JSONObject(result);int messgeCount = json.optInt("unreadMessageCount");AppApplication.messgeCount = messgeCount;AppApplication.getInstance().setSport();String unreadMessage = json.optString("unreadMessage");if (!TextUtils.isEmpty(unreadMessage) && !"null".equals(unreadMessage)) {List<MessgeEntity> list = GsonUtil.stringToList(unreadMessage, MessgeEntity.class);for (int i = 0; i < list.size() && i < 2; i++) {String taskMessageType = list.get(i).getTaskMessageType();if (TextUtils.isEmpty(taskMessageType)) {showNotifictionIcon(getApplication(), list.get(i), "com.haocang.messge.ui2.MessgeTabLayouFragment", false, null, null);} }}} catch (JSONException e) {e.printStackTrace();}}@Overridepublic void onErrorResponse(Response errorCode) {}};public void showNotifictionIcon(Context context, MessgeEntity entity, String fragmentName, boolean toTaskPage, String type, String taskName) {Class clazz = null;try {clazz = Class.forName("com.haocang.base.ui.CommonActivity");} catch (ClassNotFoundException e) {e.printStackTrace();}if (clazz != null) {Intent intent = new Intent(getApplication(), clazz);//点击之后进入MainActivityintent.putExtra("fragmentName", fragmentName);intent.putExtra("messageId", entity.getId());intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) entity.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);//第二个参数如果id相同会覆盖之前的所有intentNotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);String id = "channel_2";//删了会报错 。。。。。String id_normal= "channel_1";String name = "aaa";notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {String channel_id_actural=id_normal;if (entity.getMessageCategory() == 2) {channel_id_actural=id;}else {channel_id_actural=id_normal;}NotificationChannel mChannel = new NotificationChannel(channel_id_actural, name, NotificationManager.IMPORTANCE_LOW);if(entity.getMessageCategory() == 2){mChannel.setSound(sound, Notification.AUDIO_ATTRIBUTES_DEFAULT);}notificationManager.createNotificationChannel(mChannel);notification = new Notification.Builder(this).setChannelId(channel_id_actural).setContentTitle(entity.getTitle()).setContentText(entity.getContent()).setContentIntent(pendingIntent).setSmallIcon(R.mipmap.ic_mango).build();} else {NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setContentTitle(entity.getTitle()).setContentText(entity.getContent()).setSmallIcon(R.mipmap.ic_mango).setContentIntent(pendingIntent)
//                        .setDefaults(Notification.DEFAULT_SOUND).setOngoing(false);
//                    .setChannel(id);//无效if (entity.getMessageCategory() == 2) {notificationBuilder.setSound(sound, 5);} else {notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);}notification = notificationBuilder.build();}notificationManager.notify((int) entity.getId(), notification);}}}

Android中的Service模板,通过Service发送通知并修改通知的提示音相关推荐

  1. Android中bindService的使用及Service生命周期

    Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法,本文只探讨纯bindService的使用,不涉及 ...

  2. Android动态更改通知图标,修改通知标志  |  Android 开发者  |  Android Developers

    从 8.0(API 级别 26)开始,当关联的应用有活动通知时,启动器图标上会显示通知标志(也称为通知圆点).用户可以长按应用图标以显示通知(以及任何应用快捷方式),如图 1 所示. 默认情况下,这些 ...

  3. Android中使用running services查看service进程内存

    从Android 2.0开始,在Settings中加入了一个新的activity("Running Services" activity),它用于显示当前运行的每个Services ...

  4. Android中屏蔽有新短信时通知栏里的通知

    其实,要达到如题所述的效果很简单,只要注册一个广播,并设置该广播的intent-filter,同时把该intent-filter的优先级设置高于系统优先级 final String SMS_RECEI ...

  5. android通知声音oppo,oppo充电提示音

    oppo充电提示音app是一款能为安卓用户们提供的一款手机充电提示音.最近出现的苹果手机提示音是很多的.大家是不是非常的眼红呢,使用这款软件,进行安卓手机的一些提示音更换.这样也能获得更多的操作,想要 ...

  6. android中进程间通信的几种方式

    进程间通信(IPC)方式 使用Bundle 使用文件共享 使用Messenger 使用AIDL 使用COntentProvider 使用Socket 一.使用Bundle 我们都知道Android中三 ...

  7. Android中如何查看内存(上)

    文章参照自:http://stackoverflow.com/questions/2298208/how-to-discover-memory-usage-of-my-application-in-a ...

  8. Android中handler的使用及原理---学习笔记

    Handler类的基本介绍以及使用: Android中UI操作是线程不安全的操作,如果有多个线程并发操作UI组件,就会出现线程安全问题,所以Android中制定了一个规则:在Android中只允许主线 ...

  9. android原生代码中的情景模式及提示音和通知

    如下介绍的是5.1平台中的设置应用中的情景模式及提示音和通知 设置的界面: 对应的java类:com.android.settings.SettingsActivity 对应的xml文件:xml/da ...

最新文章

  1. delphi 登录界面 主窗体 切换_winform项目——仿QQ即时通讯程序06:主界面交互逻辑...
  2. Java多线程6:synchronized锁定类方法、volatile关键字及其他
  3. 地图点击省跳转到市_城市天际线导入真实世界地图教程
  4. 这款AI语音模型让派大星承认自己是钢铁侠,造假小扎对口型,火到挤爆服务器|在线可玩...
  5. SQL查询语句精华文章(转)
  6. ASP.NET Core on K8S深入学习(10)K8S包管理器Helm-Part 1
  7. python画图颜色表示大小变化_Python matplotlib减少色条标签的大小
  8. Mac Crack路欧词典(所有版本)
  9. Windows 8.1安装python出现api-ms-win-crt-runtime-l1-1-0.dll
  10. 拓客系统专用服务器,北京拓客系统
  11. BT种子 kitty
  12. C#实现远程关机与远程开机(唤醒)
  13. 上海市政府颁布智能汽车牌照,蔚来汽车成首批获此资格企业
  14. n一加关闭小部件_小部件
  15. AutoCAD Civil 3D贴图
  16. 百度定位 Android 经纬度出现4.9E-324 问题解决
  17. 电脑计算机c盘打不开怎么办,Win7系统电脑C盘打不开怎么办_Win7系统电脑C盘打不开的解决方法 - 系统家园...
  18. (创建型)设计模式——工厂模式(factory)
  19. 高通MSM8974芯片参考资料免费下载
  20. 人工智能应届毕业生月薪20k,他们是如何做到的?

热门文章

  1. 响应式织梦模板婚纱照摄影类网站
  2. oracle 11g安装教程完整版
  3. 双评价技术指南2020_“双评价”技术指南(11月份版)解读
  4. android字体安装失败,字体管家安装字体失败插件
  5. shopex php5.3 无法安装,php版本导致shopex4.8.5安装的问题_PHP教程
  6. 如何快速创建腾讯云MySQL数据库并远程连接?
  7. 有啊怎么才能抗衡淘宝
  8. PBOC借/贷记IC卡终端专用参数信息
  9. 用栈实现将十进制数转换为任意进制数(2,8,16...).
  10. Windows 11 截屏快捷键被占用