Android之startForeground使用
2023-04-18 12:46:59 时间
Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。
startForegroundService
在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground()
方法以显示新服务的用户可见通知。
如果应用在此时间限制内未调用 startForeground()
,则系统将停止服务并声明此应用为 ANR。
针对Android 9(API级别28)或更高级别并使用前台服务的应用程序必须请求 FOREGROUND_SERVICE permission
。
所以现在我们需要在清单文件中添加 Foreground服务权限
允许常规应用程序使用 Service.startForeground
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
使用实例
首先创建一个服务:
public class MusicPlayerService extends Service {
private static final String TAG = MusicPlayerService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand()");
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind()");
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
修改onStartCommand代码,添加通知:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand()");
// 在API11之后构建Notification的方式
Notification.Builder builder = new Notification.Builder
(this.getApplicationContext()); //获取一个Notification构造器
Intent nfIntent = new Intent(this, MainActivity.class);
builder.setContentIntent(PendingIntent.
getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.mipmap.ic_large)) // 设置下拉列表中的图标(大图标)
.setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
.setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
.setContentText("要显示的内容") // 设置上下文内容
.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
}
在完成Notification通知消息的构建后,在Service的onStartCommand中可以使用startForeground方法来让Android服务运行在前台:
// 参数一:唯一的通知标识;参数二:通知消息。
startForeground(110, notification);// 开始前台服务
相关文章
- 一个Java程序员对2011年的回顾
- 大数据发展历程
- Android高级进阶之路【一】Android中View绘制流程浅析
- 可信服务管理(Trusted Service Manager)介绍
- GIS应用|快速开发REST空间分析服务
- 未来十年微软长盛不衰的两项战略
- 领域驱动设计模式的收益与挑战
- cocos 3.0 一键打包android平台应该注意的细节
- 数智化时代,驱动企业转型升级的“三驾马车”是什么?
- 基于MINA构建高性能的NIO应用
- 使用Rainbond实现离线环境软件交付
- 工作流引擎 jBPM 5.2 发布
- 微信小程序Minium自动化测试(三)
- 桌面应用抢先体验,这次有点料!
- 甲骨文Java专利遭拒 起诉Android侵权受挫
- 云计算的应用领域及发展前景
- Java效率真的很低吗?Android为何要采用?
- Android高级进阶之路【二】十分钟彻底弄明白 View 事件分发机制
- 庖丁解牛之-Android平台RTSP|RTMP播放器设计
- 手机直付,超级方便