服务的生命周期和更多技巧

本文详细介绍了Android服务的生命周期,强调了startService()和stopService()的使用,以及如何处理前台服务,包括创建前台服务、解决权限和通知问题。此外,还探讨了IntentService在异步任务中的应用,展示了如何自动停止服务。

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

一、服务的生命周期

和活动类似,服务也有自己的生命周期,前面使用到的onCreate()、onStartCommand()、 onBind()和onDestroy( )等方法都是在服务的生
命周期内可能回调的方法。

一旦在项目的任何位置调用了Context 的startService()方法,相应的服务就会启动起来,并回调onStartCommand()方法。

如果这个服务之前还没有创建过,onCreate()方法会先于
onStartCommand()方法执行。

服务启动了之后会一直保持运行状态,直到stopService()或
stopSelf()方法被调用。

注意,虽然每调用一次startService()方法,onStartCommand()就
会执行一次,但实际上每个服务都只会存在一个实例。所以不管调用了多少次startService()方法,只需调用一次stopService()或stopSelf()方法,服务就会停止下来了。

当调用了startService() 方法后,又去调用stopService() 方法,这时服务中的onDestroy()方法就会执行,表示服务已经销毁了。

类似地,当调用了bindService()方法后,又去调用unbindService()方 法,onDestroy()方法也会执行。

但是需要注意,我们是完全有可能对一个服务既调用了startService()方法,又调用 了bindService()方法的,这种情况下该如何才能让服务销毁掉呢?

根据Android系统的机制,一个服务只要被启动或者被绑定了之后,就会一直处于运行状态,必须要让以上两种条件同时不满足,服务才能被销毁。所以,这种情况下要同时调用stopService()和unbindService()方法,onDestroy()方法才会执行。

二、使用前台服务

2.1、前言:

服务几乎都是在后台运行的,但是服务的系统优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务。

如果希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台服务。

前台服务和普通服务最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。

当然有时候也可能不仅仅是为了防止服务被回收掉才使用前台服务的,有些项目由于特殊的需求会要求必须使用前台服务,比如说某些天气预报应用,它的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息。

2.2、创建一个前台服务

2.2.1、沿用上一篇博客“Service服务”的项目

2.2.2、修改MyService中的onCreate()方法如下

@Override
    public void onCreate() {
        super.onCreate();
        Log.d("MyService" , "onCreate executed");
        Intent intent = new Intent(this, MainActivity.class);

        String CHANNEL_ONE_ID = "com.primedu.cn";
        String CHANNEL_ONE_NAME = "Channel One";
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_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);
        }

        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("This is content title")
                .setContentText("This is content text")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources() , R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .setChannelId(CHANNEL_ONE_ID)
                .build();

        startForeground(1 , notification);

    }

2.2.3、Notification启动时,startForeground报错问题解决

第一个权限问题报错
startForeground requires android.permission.FOREGROUND_SERVICE

Manifest增加以下权限:

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

第二个问题,Android 8.0以上需要Notification需要设置个Channel
android.app.RemoteServiceException: Bad notification for startForeground

String CHANNEL_ONE_ID = "com.primedu.cn";
 String CHANNEL_ONE_NAME = "Channel One";
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_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);
        }

再新增一句.setChannelId(CHANNEL_ONE_ID)

2.3、启动程序

点击Start Service或Bind Service按钮,MyService 就会以前台服务的模式启动了,并且在系统状态栏会显示一个通知图标,下拉状态栏后可以看到该通知的详细内容,如下所示:
在这里插入图片描述

在这里插入图片描述

三、使用IntentService

我们知道,服务中的代码都是默认运行在主线程当中的,如果直接在服务里去处理一些耗时的逻辑,就很容易出现ANR ( Application Not Responding)的情况。

所以这个时候就需要用到Android多线程编程的技术了,在服务的每个具体的方法里开启一个子线程,然后在这里去处理那些耗时的逻辑。因此,一个比较标准的服务就可以写成
如下形式:

public class MyService extends Service{
...
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       new Thread(new Runnable() {
           @Override
           public void run() {
               //处理具体的逻辑
           }
       }).start();
       return super.onStartCommand(intent , flags , startId);
    }
}

但是,这种服务一旦启动之后,就会一直处于运行状态,必须调用stopService()或者stopSelf()方法才能让服务停止下来。所以,如果想要实现让一个服务在执行完毕后自动停止
的功能,就可以这样写:

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       new Thread(new Runnable() {
           @Override
           public void run() {
               //处理具体的逻辑
               stopSelf();
           }
       }).start();
       return super.onStartCommand(intent , flags , startId);
    }

为了可以简单地创建一个异步的、会自动停止的服务,Android 专门提供了一个IntentService类。

新建一个MyIntentService类继承自IntentService,代码如下所示:

package com.example.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyIntentService extends IntentService {
    public MyIntentService(){
        super("MyIntentService");//调用父类的有参构造函数
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //打印当前线程的id
        Log.d("MyIntentService" , "Thread id is" + Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService" , "onDestroy executed");
    }
}

这里首先要提供一个无参的构造函数,并且必须在其内部调用父类的有参构造函数。

然后要在子类中去实现onHandleIntent()这个抽象方法,在这个方法中可以去处理一些 具体的逻辑,而且不用担心ANR的问题,因为这个方法已经是在子线程中运行的了。

这里为了证实一下,我们在onHandleIntent( )方法中打印了当前线程的id。另外根据IntentService的特性,这个服务在运行结束后应该是会自动停止的,所以我们又重写了onDestroy()方法, 在这里也打印了一行日志,以证实服务是不是停止掉了。

由于这里是手动创建的Service,所以需要到AndroidManifest.xml中注册,如下:
在这里插入图片描述

修改activity_ main.xml 中的代码,加入一个用于启动MyIntentService这个服务的按钮,如下所示:

 <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start_intent_service"
        android:text="Start IntentService"/>

修改MainActivity 中的代码,如下所示:

package com.example.servicetest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MyService.DownloadBinder downloadBinder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (MyService.DownloadBinder)iBinder;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
............

        Button startIntentService = (Button) findViewById(R.id.start_intent_service);
        startIntentService.setOnClickListener(this);
    }




    @Override
    public void onClick(View view) {
        switch (view.getId()){
            ..........
            case R.id.start_intent_service:
                //打印主线程的id
                Log.d("MainActivity" , "Thread id is " + Thread.currentThread().getId());
                Intent intent = new Intent(this, MyIntentService.class);
                startService(intent);
                break;
            default:
                break;
        }
    }
}

在Start IntentService按钮的点击事件里面去启动MyIntentService这个服务,并在这里打印了一下主线程的id,稍后用于和IntentService进行比对。

点击Start IntentService按钮后,效果如下:
在这里插入图片描述
可以看到,不仅MyIntentService和MainActivity所在的线程id不一样,而且onDestroy()方法也得到了执行,说明MyIntentService 在运行完毕后确实自动停止了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值