android-安卓如何开启前台服务?foregroundService的使用方法,什么是前台服务?

Demo代码,android studio平台可直接运行
点击打开Demo

  • Android技术生活-QQ交流群:723592501

1.AndroidManifest.xml添加权限

  1. AndroidManifest.xml添加权限
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

同时在里要注册服务

   <service
            android:name="com.yfz.myapplication.ForegroundServiceTest"
            android:foregroundServiceType="mediaProjection"
            android:enabled="true"
            >
        </service>

2. 继承 Service 复写onStartCommand


    private NotificationManager notificationManager;
    private Notification notification;
    private NotificationChannel notificationChannel;
    private final static String NOTIFICATION_CHANNEL_ID = "CHANNEL_ID";
    private final static String NOTIFICATION_CHANNEL_NAME = "CHANNEL_NAME";
    private final static int FOREGROUND_ID=1;
    
 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            );
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        intent = new Intent(getApplicationContext(), MainActivity.class);  //点击通知栏后想要被打开的页面MainActivity.class
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);  //点击通知栏触发跳转
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notification = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("标题:测试文案")
                    .setContentText("内容:你好,点击打开app主页")
                    .setContentIntent(pendingIntent)
                    .build();
        }
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(FOREGROUND_ID, notification);
        return Service.START_STICKY;
    }
4.在需要的地方开启Service
    Intent service = new Intent(getApplicationContext(), ForegroundServiceTest.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.startService(service);
        }

什么是前台服务?

前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。
官方描述:
A foreground service(前台服务) is a service that’s considered to be(被用户所认可的) something the user is actively aware of and thus not a candidate for(而不是一个候选的,可以在内存不足时,被系统杀死的) the system to kill when low on memory. A foreground service must provide a notification for the status bar(前台服务必须提供一个显示通知), which is placed under the “Ongoing” heading(它是不可以忽略的), which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.(意思是通知信息不能被忽略,除非服务停止或主动移除,否则将一直显示。)


2.为什么要使用前台服务
在一般情况下,Service几乎都是在后台运行,一直默默地做着辛苦的工作。但这种情况下,后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收。
  那么,如果我们希望Service可以一直保持运行状态且不会在内存不足的情况下被回收时,可以选择将需要保持运行的Service设置为前台服务。

例:
App中的音乐播放服务应被设置在前台运行(前台服务)——在App后台运行时,便于用户明确知道它的当前操作、在状态栏中指明当前歌曲信息、提供对应操作。


1.Service的相关配置列表

<service android:description="string resource"
         android:directBootAware=["true" | "false"]
         android:enabled=["true" | "false"]
         android:exported=["true" | "false"]
         android:foregroundServiceType=["connectedDevice" | "dataSync" |
                                        "location" | "mediaPlayback" | "mediaProjection" |
                                        "phoneCall"]
         android:icon="drawable resource"
         android:isolatedProcess=["true" | "false"]
         android:label="string resource"
         android:name="string"
         android:permission="string"
         android:process="string" >
    . . .
</service>

android:description
service的描述文字。

android:directBootAware
是否在用户解锁时直接启动。

android:enabled
是否可以被Android系统实例化。

android:exported
是否可以跟其他应用的组件直接交互。

android:foregroundServiceType
指定该服务是满足特定用例的前台服务。

android:icon
代表Service的图标。

android:isolatedProcess
如果设置为true,则此服务将在与系统其余部分隔离的特殊进程中运行,并且没有自己的权限,与它的唯一通信只能通过Service API(绑定和启动)。

android:label
可以显示给用户的服务标签。

android:name
实现Service子类的完全类名。

android:permission
访问Service必须的权限。

android:process
Service运行的进程名称。


相关引用文章:
作者:紫豪
链接:https://www.jianshu.com/p/5505390503fa

作者:老杨的互联网开发基地
链接:https://www.jianshu.com/p/cd6c703bc6ee

作者:Mars-xq
链接:https://blog.csdn.net/sinat_31057219/article/details/110004418

  • 12
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值