使用前台服务

  服务的系统优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务。如果你希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台服务。
1、在AndroidManifest.xml配置服务

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

2、编写服务类

package com.test.testapplication1;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class MyService extends Service {

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

    @Override
    public void onCreate() {
        super.onCreate();
        String CHANNEL_ONE_ID = "CHANNEL_ONE_ID";
        String CHANNEL_ONE_NAME = "CHANNEL_ONE_NAME";
        NotificationChannel notificationChannel = null;
        //进行8.0的判断
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //配置通知渠道id,渠道名称(用户可以看到),渠道优先级
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
            //配置通知出现时的闪灯(如果 android 设备支持的话)
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            //是否允许这个渠道下的通知显示角标,默认会显示角标
            notificationChannel.setShowBadge(true);
                //锁屏状态下显示通知图标及标题 1、VISIBILITY_PUBLIC 在所有锁定屏幕上完整显示此通知
                // 2、VISIBILITY_PRIVATE 隐藏安全锁屏上的敏感或私人信息
                // 3、VISIBILITY_SECRET 不显示任何部分
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
        }

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = null;
        NotificationCompat.Builder builder = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            builder = new NotificationCompat.Builder(this,CHANNEL_ONE_ID);
        }else{
            builder = new NotificationCompat.Builder(this);
        }
        notification = builder.setTicker("Nature")
                .setSmallIcon(R.drawable.notice_small)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.notice_big))
                .setContentTitle("这是一个标题")
                .setContentIntent(pendingIntent)
                .setContentText("这是一个内容")
                .build();
        notification.flags = Notification.FLAG_NO_CLEAR;
        startForeground(1, notification);
    }
}

3、启动、停止服务

package com.test.testapplication1;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Intent intent = new Intent(MainActivity.this,MyService.class);
        findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             	//启动服务
                startService(intent);

            }
        });
        findViewById(R.id.btn_stop_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//停止服务
                stopService(intent);
            }
        });
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当我们需要在Android应用中执行一些长时间运行的任务时,可以使用前台服务前台服务是一种在通知栏中显示持续运行通知的服务,以提醒用户应用正在后台执行任务。 以下是一个简单的Android前台服务的例子: 1. 创建一个Service类,继承自android.app.Service,并重写onCreate()、onStartCommand()和onDestroy()方法。 ```java public class MyForegroundService 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=".MyForegroundService" android:enabled="true" android:exported="false" /> ``` 3. 在需要启动前台服务的地方,使用以下代码启动服务。 ```java Intent serviceIntent = new Intent(this, MyForegroundService.class); ContextCompat.startForegroundService(this, serviceIntent); ``` 这样,当启动前台服务时,会在通知栏中显示一个持续运行的通知,告知用户应用正在后台执行任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值