服务
1. 服务的概念
*服务运行于后台,其存在于所属应用的进程。当所属应用的进程被杀死,则服务也被杀死。
*服务并不会主动开启新线程执行任务,服务的所有代码都是默认由主线程执行。
*为了不阻塞主线程,服务中的具体任务需要手动创建子线程来执行。
2. 异步消息处理机制
异步消息处理机制需要使用的组件包括:Message对象、Handler对象(主线程和子线程共用一个对象)、MessageQueue对象(一个线程
有唯一一个,自动创建)、Looper((一个线程有唯一一个,自动创建)。
步骤:
- 在主线程创建Handler对象,在子线程中创建Message对象,并给Message设定一些参数(what作为id、obj属性存对象等);
- 在子线程中根据业务需要调用Handler对象的sendMessage()方法,将Message对象存入到主线程的MessageQueue对象中;
- 主线程的Looper对象将MessageQueue对象取出并调用Handler对象的handleMessage()方法处理Message对象。
3. 异步消息处理抽象类AsyncTask
/**
* <Params, Progress, Result>
* Params: 创建当前异步任务时需要传入的参数,一般为Void
* Progress: 更新异步任务进度时,需要调用publishProgress(progress)方法,Progress就是参数类型
* Result:异步任务的返回参数类型
* * */
class MyAsyncTask extends AsyncTask<Void,Integer,Boolean> {
@Override protected void onPreExecute() {
super.onPreExecute();
}
/**
* 在doInBackground中执行任务逻辑,以及更新进度
* */
@Override
protected Boolean doInBackground(Void... voids) {
int progress = 0;
while (progress < 100){
progress += 1;
SystemClock.sleep(20);
publishProgress(progress);
}
return true;
}
/**
* 当doInBackground()方法调用publishProgress(progress),该方法
* 就会被调用,progress作为参数。
* */
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
/**
* 当doInBackground()返回之后,该方法就会执行
* */
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}`
4. 服务的创建、启动和停止
`public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button startBtn, stopBtn, bindBtn,unbindBtn;
private String TAG = "主活动";
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG,"绑定");
((MyService.MyBinder)service).startDownload();
((MyService.MyBinder)service).getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG,"解绑");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button) findViewById(R.id.start_service);
stopBtn = (Button) findViewById(R.id.stop_service);
bindBtn = (Button) findViewById(R.id.bind_service);
unbindBtn = (Button) findViewById(R.id.unbind_service);
startBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
bindBtn.setOnClickListener(this);
unbindBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.start_service){
Intent intent = new Intent(this,MyService.class);
startService(intent);
Log.d(TAG,"启动服务");
}else if(id == R.id.stop_service){
Intent intent = new Intent(this,MyService.class);
stopService(intent);
Log.d(TAG,"停止服务");
}else if(id == R.id.bind_service){
Intent intent = new Intent(this,MyService.class);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
}else if(id == R.id.unbind_service){
Intent intent = new Intent(this,MyService.class);
unbindService(serviceConnection);
}
}
}`
+++++++++++++++++++++++++++++++
public class MyService extends Service {
private String TAG = "你的服务";
private IBinder myBinder;
class MyBinder extends Binder {
private String TAG = "你的Binder";
public void startDownload(){
Log.d(TAG,"开始下载");
}
public int getProgress(){
Log.d(TAG,"获取进度");
return 30;
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
if(myBinder == null){
myBinder = new MyBinder();
}
return myBinder;
}
/**
* 服务创建的时候被调用
*/
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"服务: onCreate()");
}
/**
* 服务启动的时候被调用
* @param intent
* @param flags
* @param startId
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"服务: onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
/**
* 服务销毁的时候调用,服务的销毁可以在活动中显式stop,也可以在onStartCommand()中调用stopSelf()
*/
@Override
public void onDestroy() {
Log.d(TAG,"服务: onDestroy()");
super.onDestroy();
}
}
5. IntentService
业务逻辑写进IntentService的onHandleIntent()方法中,这个方法会被自动新开的子线程执行。当方法执行完毕,子线程会自动执行销毁方法将IntentService对象关闭。

浙公网安备 33010602011771号