Android基础总结五:Service总结

本文详细介绍了Android中Service组件的基本用法,包括Service的启动、停止、生命周期回调方法及Activity与Service的绑定过程。此外还探讨了如何提高Service的优先级以避免被系统回收。

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

Service是android的四大组件之一,下面对其做下总结。

Service的基本用法

1. 新建ServiceTest继承自Service

public class ServiceTest extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("KNOWN","ServiceTest onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, int startId) {
        Log.d("KNOWN","ServiceTest onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("KNOWN","ServiceTest onBind()");
        return null;
    }
}

这里重写了onCreate(),onStartCommand(),onDestroy(),onBind()四个方法
其中onBind()方法是必须要重写的

2. 在AndroidManifest文件中注册Service

和其他三大组件一样,Service也要在androidManifest.xml中注册才能用:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.biyou.service">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ServiceTest"/>
    </application>
</manifest>

3. 启动Service

设置两个按钮来启动和停止Service:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.biyou.service.MainActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_startservice"
        android:text="Start Service"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_stopservice"
        android:text="Stop Service"/>
</LinearLayout>

按下Start Service按钮开启Service,调用startService(intent)开启Service,用到了Intent,与开启Activity一样
按下Stop Service停止Service:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.id_startservice).setOnClickListener(this);
        findViewById(R.id.id_stopservice).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.id_startservice:
                startService(new Intent(this,LocalService.class));
                break;
            case R.id.id_stopservice:
                stopService(new Intent(this,LocalService.class));
                break;
        }
    }
}

启动app,当按下Start Service按钮开启Service,从Logcat可以看到:

这里写图片描述

可以看出当启动Service的时候执行该Service的onCreate()和onStartCommand()两个方法,
再次按下Start Service按钮会怎么样呢?,这时候的Logcat日志如下:

这里写图片描述

只会执行onStartCommand()一个方法,此后多次按startservice按钮,每次都只会执行
onStartCommand()方法。why?

这是由于onCreate()方法只会在Service第一次被创建时调用,如果当前Service已经被创建过了,不管怎么调用startService(),onCreate()都不会再执行。

当按下Stop Service按钮停止Service,Logcat日志:

这里写图片描述

这是会执行Service的onDestroy()方法;

Activity绑定Service

  上面的Service的简单使用只是介绍了简单的启动和停止Service的过程,Activity启动Service后,两个组件就没有什么关系了,下面来总结下Service的另外一种启动方式,即Activity与Service绑定,继承Service类的时候,有个onBind()方法是必须要重写的,这个方法就是用于与Activity建立关联的,修改Service代码如下:

1. 新建MyBinder类继承自Binder类

public class ServiceTest extends Service {
    private MyBinder myBinder = new MyBinder();
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("KNOWN","ServiceTest onCreate");
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, int startId) {
        Log.d("KNOWN","ServiceTest onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("KNOWN","ServiceTest onBind");
        return myBinder;
    }

    class MyBinder extends Binder {
            public void playMusic()
            {
                Log.d("KNOWN","playMusic");
            }
    }
}

这里新建了一个MyBinder类继承自Binder类,里面添加了一个测试方法playMusic(),然后实例化MyBinder在onBind()中作为返回值。

2. 在Activity中bindService()

再添加两个按钮:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.biyou.service.MainActivity">
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_startservice"
        android:text="Start Service"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_stopservice"
        android:text="Stop Service"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_bindservice"
        android:text="Bind Service"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:id="@+id/id_unbindservice"
        android:text="Unbind Service"/>
</LinearLayout>

修改后的Activity代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private LocalService.MyBinder myBinder;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("KNOWN", "onServiceConnected");
            myBinder = (ServiceTest.MyBinder) iBinder;
            myBinder.playMusic();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("KNOWN", "onServiceDisconnected");

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.id_startservice).setOnClickListener(this);
        findViewById(R.id.id_stopservice).setOnClickListener(this);
        findViewById(R.id.id_bindservice).setOnClickListener(this);
        findViewById(R.id.id_unbindservice).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.id_startservice:
                startService(new Intent(this,ServiceTest.class));
                break;
            case R.id.id_stopservice:
                stopService(new Intent(this,ServiceTest.class));
                break;
            case R.id.id_bindservice:
                bindService(new Intent(this, ServiceTest.class), mServiceConnection, BIND_AUTO_CREATE);
                break;
            case R.id.id_unbindservice:
                unbindService(mServiceConnection);
                break;
        }
    }
}

上面创建了一个ServiceConnection实例,绑定Service必须使用此类,然后重写了onServiceConnected()方法和onServiceDisconnected()方法,

这两个方法分别用于与Service建立关联和解除关联时调用,onServiceConnected()方法中iBinder参数就是Service中onBind()返回的值,是MyBinder的实例,所以我们可以通过向下转型获得这个实例,有了这个实例Activity和Service之间的关系就变得非常紧密了。

现在我们可以在Activity中根据具体的场景来调用MyBinder中的任何public方法,即实现了Activity指挥Service干什么Service就去干什么的功能。

点击Bind Service按钮,调用了bindService()方法,就实现了绑定Service的功能,这个方法里面有三个参数,
第一个是Intent,第二个是刚才实例化的ServiceConnection,第三个是一个标志位,这里是BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行,Logcat如下:

这里写图片描述

点击Unbind Service按钮,执行unbindService(mServiceConnection)即可解除关联,这里面的参数是上面的ServiceConnection实例

如何销毁Service

上面介绍了两种启动Service的方法,一种是简单的startService(),另一种是bindService()
通过startService()启动的Service,要销毁它只需要执行stopService(),它会马上执行onDestroy()销毁
通过bindService()启动的Service该如何销毁呢?
由于第二中方法在绑定Service的时候指定的标志位是BIND_AUTO_CREATE,说明点击Bind Service按钮的时候Service也会被创建,销毁其实也很简单,点击一下Unbind Service按钮,将Activity和Service的关联解除就可以销毁了,点击Unbind Service按钮的logcat日志如下:

这里写图片描述

以上这两种销毁的方式都很好理解。

那么如果我们既点击了Start Service按钮,又点击了Bind Service按钮会怎么样呢?

这个时候你会发现,不管你是单独点击Stop Service按钮还是Unbind Service按钮,Service都不会被销毁,必要将两个按钮都点击一下,Service才会被销毁。也就是说,点击Stop Service按钮只会让Service停止,点击Unbind Service按钮只会让Service和Activity解除关联,一个Service必须要在既没有和任何Activity关联又处理停止状态的时候才会被销毁。

关于bindService的生命周期

如果一个service只通过bindService与其他组件进行绑定,那么当该组件销毁的时候,service也会跟着销毁,如果在bindService的同时,也startService,service则不会同时销毁。

关于提高Service的优先级

方法一:添加android:permission=”true”

<service
      android:name="com.android.vesmart.videorecording.service.RecorderService"
            android:permission="true"
            android:process="com.android.vesmart.videoserver" >
</service>

方法二:


public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
}

服务被杀死后将自动重启

方法三:在onDestory()中重新启动服务

public void onDestroy() {

     Intent intent = new Intent(this, RecorderService.class);

            intent.putExtra(RecorderService.SERVICE_FIRST_START_KEY,

                    "START_FORM_SELF");

      startService(intent); 
   }

方法四:
一般的,如果要启动一个不会被杀死的服务都要通知用户,只要通知了用户以后服务就不会被杀死,但是一旦清除这些通知,服务一样会被杀死,我们这里采取投机取巧的方法,让服务不会被第三方任务管理器杀死。

public void onCreate() {

Notification notification = new Notification();   //此处为创建前台服务,但是通知栏消息为空,这样我们就可                              以在不通知用户的情况下启动前台服务了
startForeground(1, notification); 

}

更多方法总结中……

android:process 的坑,你懂吗?

http://www.rogerblog.cn/2016/03/17/android-proess/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值