 Android多(duo)線(xian)程(cheng)編程(cheng)
							時(shi)間:2018-09-25      來源:未知
							Android多(duo)線(xian)程(cheng)編程(cheng)
							時(shi)間:2018-09-25      來源:未知 
							實現線程的兩種方式
使用繼承的方法
class MyThread extends Thread{
@Override
public void run(){
//處理(li)具體的邏輯
}
}
要啟動這個線(xian)程(cheng),在(zai)主線(xian)程(cheng)中新建一個該實例(li),調用其start()方法即可。
使用(yong)實現Runnable借口(kou)的方式
class MyThread implements Runnable{
@Override
public void run(){
//處理具體的邏(luo)輯
}
}
開啟(qi)現成時(shi),使(shi)用:
MyThread myThread = new MyThread();
new Thread(MyThread).start();
匿名類的(de)方法(fa)去實(shi)現Runnable也是一(yi)樣的(de)
new Thread(new Runnalbe(){
@Override
public void run(){
//處理具體邏輯
}
}).start();
異步操作
和很多(duo)的GUI庫一(yi)樣,Android的UI也(ye)是線程不安全(quan)的,所以,我(wo)們(men)不能在子線程中更新UI元素(su)。
我們需(xu)要(yao)通過(guo)異步的(de)操作通過(guo)子線程向主線程通信(xin)的(de)方(fang)式來(lai)將UI更新(xin)的(de)操作交給(gei)主線程來(lai)完(wan)成。
Handler和Message結合(he)傳遞的(de)方(fang)法
這里,有Message、Handler、MessageQueue和Looper在作(zuo)用(yong)。
1、Message是縣城(cheng)之間傳遞的消息。
2、Handler是處(chu)理者,用于發送和處(chu)理消息
3、MessageQueue是消(xiao)息(xi)隊列(lie)的意(yi)思,存放(fang)通過(guo)Handler發送(song)的消(xiao)息(xi)。
4、Looper是每(mei)個線程中的(de)MessageQueue的(de)管家。
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是一(yi)個抽象類,我們(men)要(yao)使用它,就要(yao)先對他進行處理。
3個參數:
1、Params在執行AsyncTask時(shi)需要傳(chuan)入的參數,可(ke)用(yong)于在后臺服務中使用(yong)。
2、Progress如果(guo)需要在界面上顯示(shi)當前的進度,使(shi)用這里的泛型(xing)作為進度單位。
3、Result任務執(zhi)行完畢(bi)后,對結果進行返回。
4個重寫的方(fang)法:
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中只需(xu)要寫入:
1new DownloadTask(txvShow, prgsDownload).execute();
即可。
服務
什(shen)么是(shi)服務:服務是(shi)Android的四大組件之一,在(zai)后臺運行(xing)
創建服務
創建(jian)一個繼承Service的類,
其中onBind方法(fa)是默認重寫的,其他的還有3個重要的方法(fa),onCreate()、onStartCommand()、onDestroy()。
1、onCreate()方法(fa)會在服務創建(jian)的時候調用
2、onStartCommand()會在每(mei)次服務啟動的時候調用
3、onDestroy()會在服(fu)務銷毀的時候調用。
每個服務都必須在AndroidManifest.xml中注(zhu)冊(ce)才能(neng)生效。
啟(qi)動和關閉服務
通(tong)過Intent我們可以來開啟和關(guan)閉服務
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);
服務(wu)器的生命(ming)周期:
略。
更多的(de)服(fu)務---前臺服(fu)務
類(lei)似于通知的(de)使用方(fang)法,在onCreate代碼中構建Notification對象,建立Intent對象,PendingIntent,setLatestEventInfo,接下來是startForeground方(fang)法
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
為了避免在(zai)主線(xian)(xian)程(cheng)(cheng)中出現耗時(shi)邏(luo)輯(ji),我們需要使用Android的(de)(de)多線(xian)(xian)程(cheng)(cheng)編程(cheng)(cheng)的(de)(de)方法,將耗時(shi)邏(luo)輯(ji)放(fang)入(ru)線(xian)(xian)程(cheng)(cheng)中進行(xing)。
@Override
public int onStartCommand(Intent intent, int flags,int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//處理耗(hao)時邏(luo)輯(ji)
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
在耗時(shi)邏輯執(zhi)行完成了之后,如果我(wo)們希望服務(wu)在處(chu)理完這些內(nei)容之后就自動(dong)關閉,呢(ni)么在耗時(shi)邏輯的后加上stopSelf()方法(fa)是個不(bu)錯(cuo)的選擇(ze)。
當然這里(li)要(yao)可以(yi)(yi)使用IntentService類,它(ta)可以(yi)(yi)簡(jian)單(dan)的創建(jian)一個異(yi)步的,會自動停止的服務。
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;

