美文网首页Android开发Android开发经验谈我爱编程
Android四大组件之服务的基本用法

Android四大组件之服务的基本用法

作者: Decade_Lin | 来源:发表于2018-06-21 17:10 被阅读33次

1. 定义一个服务

定义一个服务可以通过新建一个类并继承自Service类,然后重写Service中的一些方法,下面通过一个小例子来解释几个方法的作用

public class MyService extends Service{

    public MyService() {
    }
    
    @Override
    public Ibinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onDestory() {
        super.onDestroy();
    } 
}

可以看到,我们这里重写了OnCreate(), onStartCommand(), onDestory()这三个方法,他们是服务中最常用到的三个方法,而onBind()是一个抽象方法,它在后面的活动与服务绑定的时候会用到,现在暂时不解释。其中,onCreate()方法会在服务创建的时候调用,onStartCommand()方法会在每次服务启动的时候调用, onDestory()方法会在服务销毁的时候调用

2. 启动和停止服务

启动和停止服务主要是借助Intent来实现的,构建一个Intent对象,然后调用startService()方法和stopService()方法即可实现服务的启动和停止
下面是一个简单的启动和停止服务的例子:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button startService = findViewById(R.id.start_service);
        Button stopService= findViewById(R.id.stop_service);

        startService .setOnClickListener(this);
        stopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_download:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent ); //启动服务
                break;
            case R.id.pause_download:
                Intent stopIntent= new Intent(this, MyService.class);
                stopService(stopIntent); //停止服务
                break;
            case R.id.cancel_download:
                downloadBinder.cancelDownload();
                break;
        }
    }
}

上面的例子中如果没有手动停止服务的话,服务就会一直处于运行的状态。当在MyService中的任何一个位置调用stopSelf()方法的时候,就能实现服务自动停下来。

3. 活动与服务绑定

我们可以通过活动与服务绑定的方式,让活动与服务的联系更加紧密一些,绑定服务就需要用到服务当中的抽象方法onBind(),在活动中创建一个ServiceConnection的匿名类,然后在活动中构建一个Intent,调用bindService()方法与unbindService()方法实现服务的绑定与解绑

下面是下载功能的简单例子:我们还是用到上面的MyService类,在它内部新建一个DownloadBinder类

public class MyService extends Service{
    private DownloadBinder mBinder = new DownloadBinder();

    class DownloadBinder extends Binder {
        public void startDownload() {
            Log.d("MyService", "startDownload");
        }
        
        public void stopDownload() {
            Log.d("MyService", "stopDownload");
        }
    }

    @Override
    public Ibinder onBind(Intent intent) {
        return mBinder;
    }
...
}

下面是活动中的部分代码,ServiceConnection类中的onServiceConnected()方法和onServiceDisconnected()方法分别会在活动与服务绑定和解绑的时候调用

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MyService.DownloadBinder downloadBinder;

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

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        Button bindService= findViewById(R.id.bind_service);
        Button unbindService= findViewById(R.id.unbind_service);

        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            ...
            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;
        }
    }
}

相关文章

网友评论

本文标题:Android四大组件之服务的基本用法

本文链接:https://www.haomeiwen.com/subject/xirfyftx.html