實現線程的兩種方式
使用繼承的方法
class MyThread extends Thread{
@Override
public void run(){
//處理具體的邏輯
}
}
要啟動這個線程,在主線程中新建一個該實例,調用其start()方法即可。
使用實現Runnable借口的方式
class MyThread implements Runnable{
@Override
public void run(){
//處理具體的邏輯
}
}
開啟現成時,使用:
MyThread myThread = new MyThread();
new Thread(MyThread).start();
匿名類的方法去實現Runnable也是一樣的
new Thread(new Runnalbe(){
@Override
public void run(){
//處理具體邏輯
}
}).start();
異步操作
和很多的GUI庫一樣,Android的UI也是線程不安全的,所以,我們不能在子線程中更新UI元素。
我們需要通過異步的操作通過子線程向主線程通信的方式來將UI更新的操作交給主線程來完成。
Handler和Message結合傳遞的方法
這里,有Message、Handler、MessageQueue和Looper在作用。
1、Message是縣城之間傳遞的消息。
2、Handler是處理者,用于發送和處理消息
3、MessageQueue是消息隊列的意思,存放通過Handler發送的消息。
4、Looper是每個線程中的MessageQueue的管家。
Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case UPDATA_TEXT:
txvHello.setText("Nice to meet you!");
break;
default:
break;
}
}
};
8new Thread(new Runnable() {
@Override
public void run() {
Message msg = new Message();
msg.what = UPDATA_TEXT;
handler.sendMessage(msg);
}
}).start();
使用Async Task
Async Task是一個抽象類,我們要使用它,就要先對他進行處理。
3個參數:
1、Params在執行AsyncTask時需要傳入的參數,可用于在后臺服務中使用。
2、Progress如果需要在界面上顯示當前的進度,使用這里的泛型作為進度單位。
3、Result任務執行完畢后,對結果進行返回。
4個重寫的方法:
1、onPreExecute()
2、DoInBackground(。。。)
3、onProgressUpdate(。。。)
4、onPostExecute(Result)
public class DownloadTask extendsAsyncTask{
TextView txvDownloading;
ProgressBar progressBar;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setMax(100);
}
public DownloadTask(TextView txvDownloading, ProgressBar progressBar) {
this.txvDownloading = txvDownloading;
this.progressBar = progressBar;
}
@Override
protected Integer doInBackground(Void... params) {
int count = 0;
for (int i =100; i > 0; i-- ){
count++;
publishProgress(count);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return count;
}
@Override
protected void onProgressUpdate(Integer... values) {
int a = values[0];
Log.d("TAG",a+"");
progressBar.setProgress(a);
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer.equals(100)){
txvDownloading.setText("Done");
}else{
txvDownloading.setText("downloading");
}
}
}
在Mainactivity中只需要寫入:
1new DownloadTask(txvShow, prgsDownload).execute();
即可。
服務
什么是服務:服務是Android的四大組件之一,在后臺運行
創建服務
創建一個繼承Service的類,
其中onBind方法是默認重寫的,其他的還有3個重要的方法,onCreate()、onStartCommand()、onDestroy()。
1、onCreate()方法會在服務創建的時候調用
2、onStartCommand()會在每次服務啟動的時候調用
3、onDestroy()會在服務銷毀的時候調用。
每個服務都必須在AndroidManifest.xml中注冊才能生效。
啟動和關閉服務
通過Intent我們可以來開啟和關閉服務
switch (v.getId()){
case R.id.btn_start:
Intent startTntent = new Intent(this, MyService.class);
startService(startTntent);
break;
case R.id.btn_stop:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
default:
break;
}
onBind方法,綁定服務
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("TAG","StartDownload");
}
public int getProgress(){
Log.d("TAG","getProgress executed");
return 0;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private ServiceConnection connection = newServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
case R.id.btn_bindstart:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
break;
case R.id.btn_bindstop:
unbindService(connection);
服務器的生命周期:
略。
更多的服務---前臺服務
類似于通知的使用方法,在onCreate代碼中構建Notification對象,建立Intent對象,PendingIntent,setLatestEventInfo,接下來是startForeground方法
public void onCreate() {
super.onCreate();
Notification notification = newNotification(R.drawable.ic_launcher,"Notification comes",System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
startForeground(1,notification);
}
7. IntentService
為了避免在主線程中出現耗時邏輯,我們需要使用Android的多線程編程的方法,將耗時邏輯放入線程中進行。
@Override
public int onStartCommand(Intent intent, int flags,int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//處理耗時邏輯
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
在耗時邏輯執行完成了之后,如果我們希望服務在處理完這些內容之后就自動關閉,呢么在耗時邏輯的后加上stopSelf()方法是個不錯的選擇。
當然這里要可以使用IntentService類,它可以簡單的創建一個異步的,會自動停止的服務。
public class MyIntentService extends IntentService{
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
*
*/
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
for (int a = 10; a > 0; a--){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TAG", ""+a);
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("TAG", "onDestroy");
}
}
ase R.id.btn_intentservice:
Intent intentService = newIntent(this,MyIntentService.class);
startService(intentService);
break;