Service系列(一)创建简单的service

引言

撕书在之前的项目中,有遇到过service的内容,但是由于不是自己的scope,所以也就没有仔细看,今天刚好得空,先来看看最基本的service用法,关于service撕书会有一个系列来写。

概念

service通常总是称之为“后台服务”,其中“后台”一词是相对于前台而言的,具体是指其本身的运行并不依赖于用户可视的UI界面,因此,从实际业务需求上来理解,service的适用场景应该具备以下条件:

  • 并不依赖于用户可视的UI界面(当然,这一条其实也不是绝对的,如前台Service就是与Notification界面结合使用的)
  • 具有较长时间的运行特性

创建服务

AndroidManifest.xml

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

    <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=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

我们看到在AndroidManifest.xml中在我们创建Myservice的时候就会自动创建service。
activity_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:id="@+id/start_service"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:id="@+id/stop_service"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service"
        android:id="@+id/bind_service"
         />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/unbind_service"
        android:text="Unbind Service"/>
</LinearLayout>

MainActivity

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;
    private MyService.DownloadManager downloadManager;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            downloadManager = (MyService.DownloadManager)service;
            downloadManager.startDownload();
            downloadManager.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService = findViewById(R.id.start_service);
        stopService = findViewById(R.id.stop_service);
        bindService = findViewById(R.id.bind_service);
        unbindService = findViewById(R.id.unbind_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.start_service:
                Intent startIntent = new Intent(this,MyService.class);
                startService(startIntent);
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);
                break;
            case R.id.bind_service:
                Intent bindIntent = new Intent(this,MyService.class);
                bindService(bindIntent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.unbind_service:
                Intent unbindIntent = new Intent(this,MyService.class);
                unbindService(connection);
                break;
            default:
                break;
        }
    }
}

MyService

import android.app.DownloadManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private DownloadManager mBinder = new DownloadManager();
    class DownloadManager extends Binder{
        public void startDownload(){
            Log.i("MYSERVICE","startDownload executed");
        }
        public void getProgress(){
            Log.i("MYSERVICE","getProgress executed");
//            return 0;
        }
    }
    public MyService() {
    }
    //onBind是一个抽象方法,所以必须在子类中实现
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return mBinder;
    }
    //处理事情的逻辑->重写service中的方法onCreate,onDestroy,onStartCommand
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MYSERVICE","onCreate executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MYSERVICE","onStartCommand executed");
        return super.onStartCommand(intent, flags, startId);
    }

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

服务的生命周期

一旦在项目的任何位置调用了Context的startService()方法,相应的服务就会启动起来,并回调onStartCommand()方法。如果这个服务之前还没创建,onCreate方法会先于onStartComman方法执行。服务启动了之后会一直保持运行状态,直到stopService或stopSelf方法被调用。注意,虽然每调用一次startService方法,onStartCommand就会执行,但实际上每个服务都只会存在一个实例。所以不管调用了多少次startService,只需要调用一次stopService或stopSelf方法,服务就会停止下来了。
另外,还可以调用Context的bindService来获取一个服务的持久连接,这是就会回调服务中的onBind方法。类似地,如果这个服务之前还没有创讲过,onCreate方法就会先于onBind方法执行。之后,调用可以获取到onBind方法里返回的IBinder对象的实例,这样就能自由地和服务通信了。只要嗲用方和服务之间的连接没有断开,服务就会一直保持运行状态。
当调用了startService方法后,又去嗲用stopService方法,这是服务中的onDestroy方法就会执行,表示服务已经销毁了。类似,当调用bindService方法后,又去调用unbindService方法,onDestroy方法也会执行。如果同时调用了startService和bindService的情况下,就必须同时执行stopService和unbindService方法后,onDestroy方法才会执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值