Android通知栏前台服务
Android通知栏前台服务
一、前台服务的简单介绍
前台服务是那些被认为用户知道且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。
最常见的表现形式就是音乐播放服务,应用程序后台运行时,用户可以通过通知栏,知道当前播放内容,并进行暂停、继续、切歌等相关操作。
二、为什么使用前台服务
后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收,为了保持后台服务的正常运行及相关操作,可以选择将需要保持运行的Service设置为前台服务,从而使APP长时间处于后台或者关闭(进程未被清理)时,服务能够保持工作。
三.前台服务的详细使用
创建服务内容,如下(四大组件不要忘记清单文件进行注册,否则启动会找不到服务);
public class ForegroundService extends Service {
private static final String TAG = ForegroundService.class.getSimpleName(); @Override public void onCreate() { super.onCreate(); Log.e(TAG, "onCreate"); } @Nullable @Override public IBinder onBind(Intent intent) { Log.e(TAG, "onBind"); return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); }
}
创建服务通知内容,例如音乐播放,蓝牙设备正在连接等:
/**
- 创建服务通知
*/
private Notification createForegroundNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // 唯一的通知通道的id. String notificationChannelId = "notification_channel_id_01"; // Android8.0以上的系统,新建消息通道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //用户可见的通道名称 String channelName = "Foreground Service Notification"; //通道的重要程度 int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance); notificationChannel.setDescription("Channel description"); //LED灯 notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); //震动 notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); if (notificationManager != null) { notificationManager.createNotificationChannel(notificationChannel); } } NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId); //通知小图标 builder.setSmallIcon(R.drawable.ic_launcher); //通知标题 builder.setContentTitle("ContentTitle"); //通知内容 builder.setContentText("ContentText"); //设定通知显示的时间 builder.setWhen(System.currentTimeMillis()); //设定启动的内容 Intent activityIntent = new Intent(this, NotificationActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); //创建通知并返回 return builder.build();
}
启动服务时,创建通知:
@Override
public void onCreate() {
super.onCreate(); Log.e(TAG, "onCreate"); // 获取服务通知 Notification notification = createForegroundNotification(); //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID startForeground(NOTIFICATION_ID, notification);
}
停止服务时,移除通知:
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy"); // 标记服务关闭 ForegroundService.serviceIsLive = false; // 移除通知 stopForeground(true); super.onDestroy();
}
判断服务是否启动及获取传递信息:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand"); // 标记服务启动 ForegroundService.serviceIsLive = true; // 数据获取 String data = intent.getStringExtra("Foreground"); Toast.makeText(this, data, Toast.LENGTH_SHORT).show(); return super.onStartCommand(intent, flags, startId);
}
以上就是前台服务的创建过程,相关注释已经很明白了,具体使用可以查看文末的Demo。
服务创建完毕,接下来就可以进行服务的启动了,启动前不要忘记在清单文件中进行前台服务权限的添加:
服务的启动和停止
//启动服务
if (!ForegroundService.serviceIsLive) {
// Android 8.0使用startForegroundService在前台启动新服务 mForegroundService = new Intent(this, ForegroundService.class); mForegroundService.putExtra("Foreground", "This is a foreground service."); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(mForegroundService); } else { startService(mForegroundService); }
} else {
Toast.makeText(this, "前台服务正在运行中...", Toast.LENGTH_SHORT).show();
}
//停止服务
mForegroundService = new Intent(this, ForegroundService.class);
stopService(mForegroundService);
关于前台服务的介绍及使用就到这里了,相关使用已上传至Github开发记录,欢迎点击查阅及Star,我也会继续补充其它有用的知识及例子在项目上。
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
Handler 中的 handleMessage 所在线程是由什么决定的?
大多数情况下,handleMessage所在线程和 handler 初始化所在的线程相同,但 handler 初始化的时候可以传入一个 Looper 对象,此时handleMessage所在线程和参数looper所在线程相同。 1. 含参构造public Handler(Looper looper) class MainActivity : AppCompatActivity() { var handler: Handler? = null var looper: Looper? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) looper = Looper.getMainLooper() val thread = object : Thread() { override fun run() { super.run() Log.e("abc", "--- Runnabl...
- 下一篇
[ASP.NET Core 3.1]浏览器嗅探解决部分浏览器丢失Cookie问题
[ASP.NET Core 3.1]浏览器嗅探解决部分浏览器丢失Cookie问题看了前文的同学们应该都知道,搜狗、360等浏览器在单点登录中反复重定向,最终失败报错。 原因在于,非Chrome80+浏览器不识别Cookie上的SameSite=none属性值,导致认证Cookie在后续请求中被抛弃。 截至2020/3/30号,非Chrome浏览器测试包含两种结果: case1:可设置cookie的samesite=none, 浏览器可读取该cookiecase2:对cookie设置samesite=none, 浏览器不能读取该cokie浏览器 最新版本号 结果 备注IE 11 case1 win10Edge 44.18362.449.0 case1 2020/2/15开始使用chrome内核/70.0.3538.102Firefox 74 case1 360急速浏览器 12.0.1190.0 case1 基于chromium78搜狗浏览器 8.6.1.31812 case2 User-Agent: Chrome/65.0.3314.0猎豹安全浏览器 6.5.115 case2 User...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
-
Docker使用Oracle官方镜像安装(12C,18C,19C)
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- CentOS8编译安装MySQL8.0.19
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- MySQL8.0.19开启GTID主从同步CentOS8
- CentOS7,8上快速安装Gitea,搭建Git服务器
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
推荐阅读
最新文章
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- CentOS6,CentOS7官方镜像安装Oracle11G
- SpringBoot2整合Redis,开启缓存,提高访问速度
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Hadoop3单机部署,实现最简伪集群
- MySQL8.0.19开启GTID主从同步CentOS8
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果