我是靠谱客的博主 危机蜻蜓,这篇文章主要介绍Android之startForeground使用,现在分享给大家,希望可以做个参考。

image.png

Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。

startForegroundService

在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。

如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

针对Android 9(API级别28)或更高级别并使用前台服务的应用程序必须请求 FOREGROUND_SERVICE permission

所以现在我们需要在清单文件中添加 Foreground服务权限

允许常规应用程序使用 Service.startForeground

复制代码
1
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

使用实例

首先创建一个服务:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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代码,添加通知:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@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服务运行在前台:

复制代码
1
2
// 参数一:唯一的通知标识;参数二:通知消息。 startForeground(110, notification);// 开始前台服务

最后

以上就是危机蜻蜓最近收集整理的关于Android之startForeground使用的全部内容,更多相关Android之startForeground使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部