記錄2

activity service 之間通信


轉載 http://blog.csdn.net/xiaanming/article/details/9750689

在Android中,Activity主要負責前臺頁面的展示,Service主要負責需要長期運行的任務,所以在我們實際開發中,就會常常遇到Activity與Service之間的通信,我們一般在Activity中啓動後臺Service,通過Intent來啓動,Intent中我們可以傳遞數據給Service,而當我們Service執行某些操作之後想要更新UI線程,我們應該怎麼做呢?接下來我就介紹兩種方式來實現Service與Activity之間的通信問題

  • 通過Binder對象

當Activity通過調用bindService(Intent service, ServiceConnection conn,int flags),我們可以得到一個Service的一個對象實例,然後我們就可以訪問Service中的方法,我們還是通過一個例子來理解一下吧,一個模擬下載的小例子,帶大家理解一下通過Binder通信的方式

首先我們新建一個工程Communication,然後新建一個Service類

package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {
	/**
	 * 進度條的最大值
	 */
	public static final int MAX_PROGRESS = 100;
	/**
	 * 進度條的進度值
	 */
	private int progress = 0;

	/**
	 * 增加get()方法,供Activity調用
	 * @return 下載進度
	 */
	public int getProgress() {
		return progress;
	}

	/**
	 * 模擬下載任務,每秒鐘更新一次
	 */
	public void startDownLoad(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(progress < MAX_PROGRESS){
					progress += 5;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}
		}).start();
	}


	/**
	 * 返回一個Binder對象
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new MsgBinder();
	}
	
	public class MsgBinder extends Binder{
		/**
		 * 獲取當前Service的實例
		 * @return
		 */
		public MsgService getService(){
			return MsgService.this;
		}
	}

}
上面的代碼比較簡單,註釋也比較詳細,最基本的Service的應用了,相信你看得懂的,我們調用startDownLoad()方法來模擬下載任務,然後每秒更新一次進度,但這是在後臺進行中,我們是看不到的,所以有時候我們需要他能在前臺顯示下載的進度問題,所以我們接下來就用到Activity了

Intent intent = new Intent("com.example.communication.MSG_ACTION");  
bindService(intent, conn, Context.BIND_AUTO_CREATE);

通過上面的代碼我們就在Activity綁定了一個Service,上面需要一個ServiceConnection對象,它是一個接口,我們這裏使用了匿名內部類

	ServiceConnection conn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//返回一個MsgService對象
			msgService = ((MsgService.MsgBinder)service).getService();
			
		}
	};

在onServiceConnected(ComponentName name, IBinder service) 回調方法中,返回了一個MsgService中的Binder對象,我們可以通過getService()方法來得到一個MsgService對象,然後可以調用MsgService中的一些方法,Activity的代碼如下

package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	private MsgService msgService;
	private int progress = 0;
	private ProgressBar mProgressBar;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		//綁定Service
		Intent intent = new Intent("com.example.communication.MSG_ACTION");
		bindService(intent, conn, Context.BIND_AUTO_CREATE);
		
		
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
		Button mButton = (Button) findViewById(R.id.button1);
		mButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//開始下載
				msgService.startDownLoad();
				//監聽進度
				listenProgress();
			}
		});
		
	}
	

	/**
	 * 監聽進度,每秒鐘獲取調用MsgService的getProgress()方法來獲取進度,更新UI
	 */
	public void listenProgress(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(progress < MsgService.MAX_PROGRESS){
					progress = msgService.getProgress();
					mProgressBar.setProgress(progress);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			}
		}).start();
	}
	
	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//返回一個MsgService對象
			msgService = ((MsgService.MsgBinder)service).getService();
			
		}
	};

	@Override
	protected void onDestroy() {
		unbindService(conn);
		super.onDestroy();
	}


}
其實上面的代碼我還是有點疑問,就是監聽進度變化的那個方法我是直接在線程中更新UI的,不是說不能在其他線程更新UI操作嗎,可能是ProgressBar比較特殊吧,我也沒去研究它的源碼,知道的朋友可以告訴我一聲,謝謝!

上面的代碼就完成了在Service更新UI的操作,可是你發現了沒有,我們每次都要主動調用getProgress()來獲取進度值,然後隔一秒在調用一次getProgress()方法,你會不會覺得很被動呢?可不可以有一種方法當Service中進度發生變化主動通知Activity,答案是肯定的,我們可以利用回調接口實現Service的主動通知,不理解回調方法的可以看看 http://blog.csdn.net/xiaanming/article/details/8703708

新建一個回調接口

public interface OnProgressListener {
	void onProgress(int progress);
}
MsgService的代碼有一些小小的改變,爲了方便大家看懂,我還是將所有代碼貼出來

package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MsgService extends Service {
	/**
	 * 進度條的最大值
	 */
	public static final int MAX_PROGRESS = 100;
	/**
	 * 進度條的進度值
	 */
	private int progress = 0;
	
	/**
	 * 更新進度的回調接口
	 */
	private OnProgressListener onProgressListener;
	
	
	/**
	 * 註冊回調接口的方法,供外部調用
	 * @param onProgressListener
	 */
	public void setOnProgressListener(OnProgressListener onProgressListener) {
		this.onProgressListener = onProgressListener;
	}

	/**
	 * 增加get()方法,供Activity調用
	 * @return 下載進度
	 */
	public int getProgress() {
		return progress;
	}

	/**
	 * 模擬下載任務,每秒鐘更新一次
	 */
	public void startDownLoad(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(progress < MAX_PROGRESS){
					progress += 5;
					
					//進度發生變化通知調用方
					if(onProgressListener != null){
						onProgressListener.onProgress(progress);
					}
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}
		}).start();
	}


	/**
	 * 返回一個Binder對象
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new MsgBinder();
	}
	
	public class MsgBinder extends Binder{
		/**
		 * 獲取當前Service的實例
		 * @return
		 */
		public MsgService getService(){
			return MsgService.this;
		}
	}

}
Activity中的代碼如下

package com.example.communication;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	private MsgService msgService;
	private ProgressBar mProgressBar;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		//綁定Service
		Intent intent = new Intent("com.example.communication.MSG_ACTION");
		bindService(intent, conn, Context.BIND_AUTO_CREATE);
		
		
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
		Button mButton = (Button) findViewById(R.id.button1);
		mButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//開始下載
				msgService.startDownLoad();
			}
		});
		
	}
	

	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//返回一個MsgService對象
			msgService = ((MsgService.MsgBinder)service).getService();
			
			//註冊回調接口來接收下載進度的變化
			msgService.setOnProgressListener(new OnProgressListener() {
				
				@Override
				public void onProgress(int progress) {
					mProgressBar.setProgress(progress);
					
				}
			});
			
		}
	};

	@Override
	protected void onDestroy() {
		unbindService(conn);
		super.onDestroy();
	}


}
用回調接口是不是更加的方便呢,當進度發生變化的時候Service主動通知Activity,Activity就可以更新UI操作了 

當我們的進度發生變化的時候我們發送一條廣播,然後在Activity的註冊廣播接收器,接收到廣播之後更新ProgressBar,代碼如下

package com.example.communication;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	private ProgressBar mProgressBar;
	private Intent mIntent;
	private MsgReceiver msgReceiver;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//動態註冊廣播接收器
		msgReceiver = new MsgReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.example.communication.RECEIVER");
		registerReceiver(msgReceiver, intentFilter);
		
		
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
		Button mButton = (Button) findViewById(R.id.button1);
		mButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//啓動服務
				mIntent = new Intent("com.example.communication.MSG_ACTION");
				startService(mIntent);
			}
		});
		
	}

	
	@Override
	protected void onDestroy() {
		//停止服務
		stopService(mIntent);
		//註銷廣播
		unregisterReceiver(msgReceiver);
		super.onDestroy();
	}


	/**
	 * 廣播接收器
	 * @author len
	 *
	 */
	public class MsgReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			//拿到進度,更新UI
			int progress = intent.getIntExtra("progress", 0);
			mProgressBar.setProgress(progress);
		}
		
	}

}

package com.example.communication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MsgService extends Service {
	/**
	 * 進度條的最大值
	 */
	public static final int MAX_PROGRESS = 100;
	/**
	 * 進度條的進度值
	 */
	private int progress = 0;
	
	private Intent intent = new Intent("com.example.communication.RECEIVER");
	

	/**
	 * 模擬下載任務,每秒鐘更新一次
	 */
	public void startDownLoad(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(progress < MAX_PROGRESS){
					progress += 5;
					
					//發送Action爲com.example.communication.RECEIVER的廣播
					intent.putExtra("progress", progress);
					sendBroadcast(intent);
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}
		}).start();
	}

	

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startDownLoad();
		return super.onStartCommand(intent, flags, startId);
	}



	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}


}
總結:
  1. Activity調用bindService (Intent service, ServiceConnection conn, int flags)方法,得到Service對象的一個引用,這樣Activity可以直接調用到Service中的方法,如果要主動通知Activity,我們可以利用回調方法 
  2.  Service向Activity發送消息,可以使用廣播,當然Activity要註冊相應的接收器。比如Service要向多個Activity發送同樣的消息的話,用這種方法就更好 

AsyncTask的基本用法

首先來看一下AsyncTask的基本用法,由於AsyncTask是一個抽象類,所以如果我們想使用它,就必須要創建一個子類去繼承它。在繼承時我們可以爲AsyncTask類指定三個泛型參數,這三個參數的用途如下: 

1. Params 

在執行AsyncTask時需要傳入的參數,可用於在後臺任務中使用。

2. Progress 

後臺任何執行時,如果需要在界面上顯示當前的進度,則使用這裏指定的泛型作爲進度單位。

3. Result 

當任務執行完畢後,如果需要對結果進行返回,則使用這裏指定的泛型作爲返回值類型。

因此,一個最簡單的自定義AsyncTask就可以寫成如下方式:

class DownloadTask extends AsyncTask<Void, Integer, Boolean> {
  ……
}

這裏我們把AsyncTask的第一個泛型參數指定爲Void,表示在執行AsyncTask的時候不需要傳入參數給後臺任務。第二個泛型參數指定爲Integer,表示使用整型數據來作爲進度顯示單位。第三個泛型參數指定爲Boolean,則表示使用布爾型數據來反饋執行結果。 

當然,目前我們自定義的DownloadTask還是一個空任務,並不能進行任何實際的操作,我們還需要去重寫AsyncTask中的幾個方法才能完成對任務的定製。經常需要去重寫的方法有以下四個: 

1. onPreExecute() 

這個方法會在後臺任務開始執行之間調用,用於進行一些界面上的初始化操作,比如顯示一個進度條對話框等。 

2. doInBackground(Params...) 

這個方法中的所有代碼都會在子線程中運行,我們應該在這裏去處理所有的耗時任務。任務一旦完成就可以通過return語句來將任務的執行結果進行返回,如果AsyncTask的第三個泛型參數指定的是Void,就可以不返回任務執行結果。注意,在這個方法中是不可以進行UI操作的,如果需要更新UI元素,比如說反饋當前任務的執行進度,可以調用publishProgress(Progress...)方法來完成。 

3. onProgressUpdate(Progress...) 

當在後臺任務中調用了publishProgress(Progress...)方法後,這個方法就很快會被調用,方法中攜帶的參數就是在後臺任務中傳遞過來的。在這個方法中可以對UI進行操作,利用參數中的數值就可以對界面元素進行相應的更新。 

4. onPostExecute(Result) 

當後臺任務執行完畢並通過return語句進行返回時,這個方法就很快會被調用。返回的數據會作爲參數傳遞到此方法中,可以利用返回的數據來進行一些UI操作,比如說提醒任務執行的結果,以及關閉掉進度條對話框等。 

因此,一個比較完整的自定義AsyncTask就可以寫成如下方式:

class DownloadTask extends AsyncTask<Void, Integer, Boolean> {

  @Override
  protected void onPreExecute() {
    progressDialog.show();
  }

  @Override
  protected Boolean doInBackground(Void... params) {
    try {
      while (true) {
        int downloadPercent = doDownload();
        publishProgress(downloadPercent);
        if (downloadPercent >= 100) {
          break;
        }
      }
    } catch (Exception e) {
      return false;
    }
    return true;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
    progressDialog.setMessage("當前下載進度:" + values[0] + "%");
  }

  @Override
  protected void onPostExecute(Boolean result) {
    progressDialog.dismiss();
    if (result) {
      Toast.makeText(context, "下載成功", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(context, "下載失敗", Toast.LENGTH_SHORT).show();
    }
  }
}

這裏我們模擬了一個下載任務,在doInBackground()方法中去執行具體的下載邏輯,在onProgressUpdate()方法中顯示當前的下載進度,在onPostExecute()方法中來提示任務的執行結果。如果想要啓動這個任務,只需要簡單地調用以下代碼即可:

new DownloadTask().execute();

以上就是AsyncTask的基本用法,怎麼樣,是不是感覺在子線程和UI線程之間進行切換變得靈活了很多?我們並不需求去考慮什麼異步消息處理機制,也不需要專門使用一個Handler來發送和接收消息,只需要調用一下publishProgress()方法就可以輕鬆地從子線程切換到UI線程了。



\

A:onCreate->onStart->onResume

A->B(B覆蓋A)->A: A.onPause->B.onCreate->B.onstart->B.onResume->A.onStop->B.onPause->A.onRestart->A.onStart->A.onResume->B.onStop->B.onDestroy

A->B(B不覆蓋A)->A: A.onPause->B.onCreate->B.onStart->B.onResume->B.onPause->A.onResume->B.onStop->B.onDestroy



發佈了25 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章