Android Service的基本使用

1. 服务的创建

右击"src/main/java/com.example.text/"目录,new->service->servie,则可以创建一个服务类。可以看到MyService是继承Service类的。用Android Studio创建Service后,会自动在AndroidManifest.xml中注册这个Service类。如下:

<service
    android:name=".MyService"
    android:enabled="true"
    android:exported="true"></service>

服务定义后,需要重写一些方法,通常会重写onCreate(),onStartCommand()和onDestory()方法,如下:

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 {

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    //服务创建时调用
    public void onCreate(){
        super.onCreate();
        Log.d("MyService", "onCreate executed");
    }

    @Override
    //服务一启动就调用
    public int onStartCommand(Intent intent, int flags, int startId){
        Log.d("MyService", "onStartCommand executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    //服务销毁时调用
    public void onDestroy(){
        super.onDestroy();
        Log.d("MyService", "onDestroy executed");
    }
}

 

2. 启动和停止服务

在xml中定义一个ToggleButton按钮或两个Button来启动和停止服务。下面贴MainActivity.java中的代码。

import android.content.Intent;
import android.content.ServiceConnection;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

private ToggleButton ServiceTogglebutton;

//服务
ServiceTogglebutton = (ToggleButton)findViewById(R.id.serviceTogglebutton);
ServiceTogglebutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            Intent startIntent = new Intent(MainActivity.this, MyService.class);
            startService(startIntent);
        }else {
            Intent stopIntent = new Intent(MainActivity.this, MyService.class);
            stopService(stopIntent);
        }
    }
});

启动服务之后,在设置-->开发者选项-->正在运行的服务的列表中,可以看到该服务正在运行。

3. 服务的绑定与解绑

需要创建了一个ServiceConnection的匿名内部类,并实现了onServiceConnected和onServiceDisconnected两个方法。ServiceConnection可以看做是一个由Activity操作的代表,负责与Service进行连接,当Activity与Service连接成功时,会执行onServiceConnected方法,相反的,当二者断开连接的时候,会执行onServiceDisconnected方法。

MainActivity.java代码:

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;

//定义一个绑定服务的匿名类对象 connection
private ServiceConnection connection = new ServiceConnection() {
    //ServiceConnection作为绑定中介,可以在这里实例化Service中的自定义Binder,
    //并使用Binder中的自定义方法
    @Override
    //服务成功绑定时调用
    public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyService.DownloadBinder)service;
        downloadBinder.startDownload();//使用自定义的方法
    }

    @Override
    //服务成功解绑时调用
    public void onServiceDisconnected(ComponentName name) {
    }
};

//绑定与解绑
Button bindservice = (Button)findViewById(R.id.bind_service);
Button unbindservice = (Button)findViewById(R.id.unbind_service);
bindservice.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent bindIntent = new Intent(MainActivity.this, MyService.class);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);//绑定服务
    }
});
unbindservice.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent unbindIntent = new Intent(MainActivity.this, MyService.class);
        unbindService(connection);//解绑服务
    }
});

MyService.java代码

//在MyService类中,添加一个自己的Binder public类,继承Binder
//这个自定义的Binder类中,可以定义自己绑定后的功能,这个类可以在Activity中实例化
//一般可以在onServiceConnected()方法中实例化并使用
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder{
    public void startDownload(){
        Log.d("MyService", "StartDownload executed");
    }
    
    public int getProgress(){
        Log.d("MyService", "getProcess executed");
    }
}

//修改onBind()方法,返回自定义的DownloadBinder实例对象
@Override
public IBinder onBind(Intent intent){
    return mBinder;
}

参考文章

《第一行代码》(第二版)10.3 服务的基本用法

Android Service基本用法

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值