安卓前台服务的使用

1.创建一个简单的MyService继承Service

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 处理Service的逻辑
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 如果Service需要被绑定,则返回一个IBinder实例
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

2.在MyService的onCreate方法中创建通知

    String CHANNEL_ID = "channel_id_wifi";
    
    String CHANNEL_NAME = "channel_name_wifi";
    
    int NOTIFICATION_ID = 110;
    
    NotificationChannel notificationChannel;
    
    Notification notification;

    @Override
    public void onCreate() {
        // 创建通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
            notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("This is content title")
                    .setContentText("This is content text")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .build();


        } else {
            notification = new NotificationCompat.Builder(this, "my_service_channel")
                    .setContentTitle("前台服务")
                    .setContentText("服务正在运行")
                    .setSmallIcon(R.drawable.ic_launcher_background) // 替换为您的通知图标资源ID
                    .build();
        }
        startForeground(NOTIFICATION_ID, notification);
        super.onCreate();
    }

在onCreate中创建通知的优势是无论该服务是通过startService还是bindService启动的该服务,都会调用onCreate方法,所以通知都可以正常创建,除此之外,onCreate方法仅会调用一次,可以有效避免重复创建。当然,针对定制化的通知,也可根据需求在onStartCommand和onBind中进行创建。
3.在onDestroy中停止前台服务

    public void onDestroy() {
        stopForeground(true);
        super.onDestroy();
    }

4.在AndroidManifest.xml注册文件中,添加通知权限

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

5.如果当前版本是Android10的话,Android应用程序获得读写存储卡权限的情况下,需要在AndroidManifest.xml的application标签下声明

android:requestLegacyExternalStorage="true"

6.在MainActivity中启动服务
① startService:

        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);

② bindService:

        Intent serviceIntent = new Intent(this, MyService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // 当Service连接成功时调用
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                // 当Service连接断开时调用
            }
        };
        bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);

值得注意的是,如果采用的是bindService的方法,一定记得在MainActivity的onDestroy方法中及时解绑,避免内存泄漏。

    protected void onDestroy() {
        super.onDestroy();

        unbindService(connection);
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值