Android 通过构建前台服务实现Service保活

         在Android中,退出APP界面后通过startService()方法启动的服务很快就会随之停止,在一些需求中需要在退出APP界面的情况下保证Service一直在运行,其中一个方法就是将Service设置成前台服务。设置前台服务首先需要在配置文件中添加权限:

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

自定义通知消息的布局:

RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.item_notification);

如果需要实现点击效果:

Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
notification.setContentIntent(pi)

然后在Service的onStartCommand()方法中:

 Notification notification = new NotificationCompat.Builder(this, "CHANNEL")
                .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                .setContent(remoteViews)
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
        startForeground(1, notification);

安卓8之后的版本中需要在前面设置消息渠道,notification中的渠道id必须要与notificationChanel中的id相同。

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("CHANNEL", getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(getColor(R.color.black));
            notificationChannel.enableVibration(false);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(notificationChannel);
            }
        }

停止前台服务,参数代表是否删除通知栏上的通知:

stopForeground(true);

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android前台服务保活是指通过将服务设置为前台服务,使其在系统资源紧张时更难被系统杀死,从而提高服务的稳定性和可靠性。下面是一个简单的Android前台服务保活的例子: 1. 创建一个继承自Service前台服务类,例如ForegroundService: ```java public class ForegroundService extends Service { private static final int NOTIFICATION_ID = 1; private static final String CHANNEL_ID = "ForegroundServiceChannel"; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { createNotificationChannel(); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Foreground Service") .setContentText("Running") .setSmallIcon(R.drawable.ic_notification) .setContentIntent(pendingIntent) .build(); startForeground(NOTIFICATION_ID, notification); // 在这里执行你的业务逻辑 return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); stopForeground(true); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } } } ``` 2. 在AndroidManifest.xml文件中注册前台服务: ```xml <service android:name=".ForegroundService" android:enabled="true" android:exported="false" /> ``` 3. 在需要启动前台服务的地方调用startService方法: ```java Intent serviceIntent = new Intent(context, ForegroundService.class); ContextCompat.startForegroundService(context, serviceIntent); ``` 这样,当启动前台服务后,系统将会将该服务标记为前台服务,并显示一个持续运行的通知,从而提高服务的优先级,减少被系统杀死的概率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值