前台服务,Notification的使用

1.Android6.0 以下版本可以这么用,在Service的onCreate方法中

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(this, SecondActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("message")
                .setContentTitle("title")
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // manager.notify(1, notification);
        startForeground(1,notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

使用notification ,区别是用startForeground方法,这样打开的notification常驻状态栏(除非进程或者该服务被杀死)。

打开一个不在状态栏显示的notification , 第一个参数id为0即可 : startForeground(0, new Notification());
要从前台删除服务,需调用stopForeground()方法,需要一个布尔型参数,但是这个方法不终止服务。

如果该进程或者该服务被杀死,状态栏的notification也会消失。

2.Android8.0 及以上版本可以这么用,在Service的onCreate方法中

public class MyService extends Service {

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(this, SecondActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        String channelID = "1";
        String channelName = "channel_name";
        NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("message")
                .setContentTitle("title")
                .setChannelId(channelID)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        manager.notify(1, notification);
//        startForeground(1,notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

代码和之前版本相比多了一个channelID 参数,Android 8.0 必须要有的,否则notification无法显示。

Android 8.0 后台应用想启动服务就老老实实的加个notification给用户看,表示你自己在后台占着资源,杀不杀由用户决定,偷偷地在后台跑没有framework帮忙想都别想,会导致 anr+crash。

1)activity: Context.startForegroundService()

2)Service:startForeground(int id, Notification notification)(id must not be 0,notification must not be null)。

想要变成前台服务:启动服务要使用startForegroundService方法,然后必须要在5秒内调用startForeground方法,而且参数(id!=0&&notification!=null),否则导致 anr+crash。

Android8.0 需要设置通知栏,使服务变成前台服务。

但是在 Android9.0 就会出现Permission Denial: startForeground requires android.permission.FOREGROUND_SERVICE。如果是启动前台服务的话 还需要一个权限 android.permission.FOREGROUND_SERVICE

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin是一种基于Java虚拟机(JVM)的态类型编程语言,它可以用于开发各种应用程序,包括Android应用程序。前台服务是Android中一种特殊的服务类型,它可以在前台运行,并与用户进行交互。 在Kotlin中,你可以使用Android的Service类来创建前台服务。要创建一个前台服务,你需要执行以下步骤: 1. 创建一个继承自Service类的Kotlin类。 2. 在该类中重写onCreate()方法,在该方法中进行初始化工作。 3. 在onStartCommand()方法中编写服务的逻辑代码。这是服务被启动时调用的方法。 4. 在onDestroy()方法中释放资源和停止服务。 为了将服务设置为前台服务,你需要在onStartCommand()方法中调用startForeground()方法,并传递一个通知参数。这个通知将显示在系统状态栏上,并且用户可以通过点击通知与服务进行交互。 下面是一个简单的示例代码,展示了如何在Kotlin中创建一个前台服务: ```kotlin class MyForegroundService : Service() { override fun onCreate() { super.onCreate() // 初始化工作 } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // 服务逻辑代码 startForeground(1, createNotification()) // 设置为前台服务 return START_STICKY } override fun onDestroy() { super.onDestroy() // 释放资源和停止服务 } private fun createNotification(): Notification { // 创建通知 // 设置通知的标题、内容、图标等 val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Foreground Service") .setContentText("Service is running...") .setSmallIcon(R.drawable.ic_notification) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setCategory(NotificationCompat.CATEGORY_SERVICE) return notificationBuilder.build() } override fun onBind(intent: Intent?): IBinder? { return null } } ``` 这是一个简单的前台服务示例,你可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值