Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > 安卓14前端服务foregroundService权限

安卓14前端服务foregroundService权限问题解决办法

作者:周neo

Android服务(Service)是应用组件,它可以在后台执行长时间运行的操作,而不提供用户界面,这篇文章主要介绍了安卓14前端服务foregroundService权限问题解决的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

发现问题

在安卓应用开发过程中,我们会使用到service,普通的service我们只需要在AndroidMainfest.xml文件中添加service类就好

<application
    <service android:name=".service.MyService" />
</application>

前端服务foregroundService还需要添加

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

但如果只是这样,启动前端服务还是会报错

经查资料发现:

Android 14(API 34)对前台服务的权限体系进行了深度重构:

1.细分权限体系
除基础权限 FOREGROUND_SERVICE 外,必须根据服务类型声明对应的细分权限:

除基础权限 FOREGROUND_SERVICE 外,必须根据服务类型声明对应的细分权限:

  • 数据同步服务:FOREGROUND_SERVICE_DATA_SYNC
  • 位置服务:FOREGROUND_SERVICE_LOCATION
  • 媒体播放服务:FOREGROUND_SERVICE_MEDIA_PLAYBACK
  • 电话服务:FOREGROUND_SERVICE_PHONE_CALL

2.服务类型强校验

系统会严格验证 android:foregroundServiceType 属性与权限的匹配性,不匹配将抛出 SecurityException

java.lang.SecurityException: 
ForegroundServiceType dataSync requires android.permission.FOREGROUND_SERVICE_DATA_SYNC

3.通知权限前置要求

从 Android 13(API 33)开始,显示通知的前台服务必须动态请求 POST_NOTIFICATIONS 权限

解决方案

在AndroidMainfest.xml清单文件中这样添加:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

    
    <application
        <service
            android:name=".service.MyForegroundService"
            android:enabled="true"
            android:exported="false"
            android:foregroundServiceType="dataSync">
        </service>

    </application>

Java代码中前端服务实现

  @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate:");
        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "channel_id",
                    "通知",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            notificationManager.createNotificationChannel(channel);
        }

        //创建通知

        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.baseline_music_note_24)
                .setContentTitle("这是标题")
                .setContentText("这是内容")
                .build();
        startForeground(1, notification);
    }

运行如果发现通知栏中不存在,还需要进入设置->应用中打开app的通知权限

最后大家可以通过adb检查服务状态

adb shell dumpsys activity services | grep "ForegroundService"

总结 

到此这篇关于安卓14前端服务foregroundService权限问题解决办法的文章就介绍到这了,更多相关安卓14前端服务foregroundService权限内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

阅读全文