前台服务Foreground Service

前台服务是在Android中一种用户可见的服务,它在状态栏显示通知,即使系统内存紧张也不会轻易被杀死。当需要确保Service持续运行时,应将其设为前台服务。实现前台服务涉及创建通知并使用`startForeground()`方法。关闭服务则通过`stopService()`完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是前台服务

 前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不容许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有这个服务被终止或从前台主动移除通知后才能被解除。

2.为什么使用

在一般情况下,Service几乎都是在后台运行,一直默默地做着辛苦的工作。但这种情况下,后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收。

那么,如果我们希望Service可以一直保持运行状态且不会在内存不足的情况下被回收时,可以选择将需要保持运行的Service设置为前台服务。

3.如何实现

<Button
            android:onClick="Startfor"
            android:text="开启前台服务"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></Button>
public void Startfor(View view) {
        Intent intent = new Intent(this,MyService.class);
        startService(intent);
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.item);
        remoteViews.setTextViewText(R.id.tv1,"落霞与孤鹜齐飞");
        remoteViews.setTextViewText(R.id.tv2,"秋水共长天一色");
        remoteViews.setImageViewResource(R.id.iv1,R.drawable.ic_launcher_background);
        Intent intent1 = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,101,intent1,PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder=new  Notification.Builder(MyService.this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setCustomContentView(remoteViews);
        Notification notification = builder.build();
        startForeground(1,notification);
        return super.onStartCommand(intent, flags, startId);
    }

关闭前天服务

<Button
            android:onClick="Stopfor"
            android:text="关闭前台服务"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></Button>
public void Stopfor(View view) {
        Intent intent = new Intent(this,MyService.class);
        stopService(intent);//停止服务
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值