1.服务是什么
服务是Android在实现后台运行时的解决方案,适用于不用和用户有界面交互的后台长期运行任务。
注意
- 服务并不是独立的进程,它依赖于创建服务的应用程序进程,当应用被杀时,服务也终止
- 服务也不是在子线程中运行的,默认情况都是在主线程执行,因此长时操作也要开启子线程来执行。
2.多线程编程
2.1 Android异步消息处理机制:Handler
- Message:可以在线程间传递的消息,一般通过msg.what来传递想要主/子线程想要做的消息
- Handler:消息的处理者,用于发送以及处理收到的消息。
- MessageQueue:消息队列,它用于存放所有通过Handler发送的消息,这些消息则是存储在这个队列中,等待被处理。每个线程只有一个MessageQueue对象。
- Looper:MessageQueue的管家, 调用Looper的loop方法后,开始进入无限循环,发现MessageQueue中有msg的时候,就把它取出并传给Handler的handleMessage方法中。
2.2 使用AsyncTask
AsyncTask是android为开发者提供的异步工具。可以方便开发者在子线程中对UI进行操作。
private class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
//后台线程执行前的准备工作防止这个方法里
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//后台执行长时操作
@Override
protected Boolean doInBackground(Void... voids) {
return null;
}
//在doInBackground 方法中调用onProgressUpdate方法时,执行该方法(主线程里执行)
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
//后台任务执行完毕时自动调用,在主线程里执行
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
……
……
//执行AsyncTask
new MyAsyncTask.execute()
AsyncTask的三个范型参数:Params, Progress, Result:分别用来传入参数,表示进度,表示执行结果。
3.服务的基本用法
3.1 启动和停止服务
Intent intent = new Intent(this, MyService.class);
startService(intent);
stopService(intent);
3.2 Service的基本定义
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");
}
//Called when Service being created for the first time
@Override
public void onCreate() {
super.onCreate();
}
//Called when Service is called by outside every time
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//Called when Service being destroyed, recycle useless resources in this function
@Override
public void onDestroy() {
super.onDestroy();
}
}
3.3 服务和其它组件通信 Binder
在服务端(Service)创建一个binder提供给客户端(这里是Activity);客户端可以通过调用binder中的public方法来获取服务中的相关信息。
服务度端定义binder
private DownloadBinder mBinder = new DownloadBinder();
//the server side returns a IBinder for client to access opened functions of the binder
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder {
public void startDownload() {
Log.i("lyh", "start download");
}
public int getProgress() {
Log.i("lyh", "download progress");
return 0;
}
}
客户端连接服务,并获取binder
public class DownloadTestActivity extends AppCompatActivity {
private MyService.DownloadBinder mIBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIBinder = (MyService.DownloadBinder) service;
mIBinder.startDownload();
mIBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_test);
//bind service
Intent intent = new Intent(this, MyService.class);
/**
* Flag for {@link #bindService}: automatically create the service as long
* as the binding exists. Note that while this will create the service,
* its {@link android.app.Service#onStartCommand}
* method will still only be called due to an
* explicit call to {@link #startService}. Even without that, though,
* this still provides you with access to the service object while the
* service is created.
**/
bindService(intent, connection, BIND_AUTO_CREATE);
//unbind service:
//unbindService(connection);
}
}
网友评论