定义
- 后台运行,不可见,没有界面
- 优先级 高于Activity
用途
- 播放音乐,记录地理信息位置的改变,监听某种动作
注意
- 运行在主线程,不能用它来做耗时的请求或者动作
- 可以在服务中开一个线程,在线程中做耗时的动作
类型
- 本地服务:用在程序内部。 startService stopService stopSelf stopSelfResult 与 bindService unbindServicee
- 远程服务:Android 系统内部的应用程序之间。 (不可跨手机) IBinder接口。
服务与Activity的绑定
1、新建class
public class MyService extends Service {}
2、如果用startService方法,则需重写onStartCommand方法:
public int onStartCommand(Intent intent, int flags, int startId) {}
3、如果用onBind方法:(主要说明这个方法):
private DonwloadBinder mBinder = new DonwloadBinder();
class DonwloadBinder extends Binder {
public void startDownload() {
Log.d(TAG, "startDownload: ");
}
public int getProcess() {
Log.d(TAG, "getProcess: ");
return 0;
}
}
4、在mainactivity中创建connection:
private MyService.DonwloadBinder donwloadBinder;
private static final String TAG = "MainActivity";
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
donwloadBinder = (MyService.DonwloadBinder) iBinder;
donwloadBinder.startDownload();
donwloadBinder.getProcess();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
5、绑定服务:
Intent bindIntent = new Intent(this , MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
6、解除绑定:
unbindService(connection);
AsyncTask 与 Service结合使用
1、新建Task类:
public class DownloadTask extends AsyncTask<String,Integer,Integer> {}
2、重写doInBackground方法:
@Override
protected Integer doInBackground(String... strings) {
return null;
}
3、