Handler: Activity 之間通過 Handler 通訊

來源:互聯網
上載者:User

假設你已經明白下面的內容,那麼這篇部落格很適合您!

<1> Application 的作用及用法

<2> Activity、Task 以及 Application 之間的關係

<3> Handler 的用法

真的很感謝 anhenzhufeng 這位 CSDN 好友,如果不是他的虛心和認真,恐怕這篇文章難以問世!

再次感謝他在我的部落格http://blog.csdn.net/androidbluetooth/article/details/6384641#reply的提問,這篇文章送給他以及有需要的朋友們。希望這篇部落格能夠幫到您!

讀這篇部落格之前,我們看看 anhenzhufeng 的問題,見,如下:

大致說一下我的思路吧!

多個 Activity 之間可以通過 Application 共用資料,在這裡我就讓兩個 Activity 共用 Handler(更新UI,我一般使用 Handler),主 Activity 中更新 UI,另一個 Activity 發送更新UI的訊息。這樣就達到在主Activity更新UI的目的。好吧,具體看代碼!

1. 主 Activity 的 main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextViewandroid:id="@+id/tv"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="changed before: This is MasterActivity!"    /><Button android:layout_marginTop="15dip"android:id="@+id/btn_to"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="To OtherActivity"/>    </LinearLayout>

2. 主 Activity 的Java 代碼

package mark.zhang;import android.app.Activity;import android.content.Intent;import android.graphics.Color;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MasterActivity extends Activity {// 用於msg.what值private static final int CHANGED = 0x0010;private Button btn_to = null;private TextView tv = null;private MyHandler handler = null;private MyAPP mAPP = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mAPP = (MyAPP) getApplication();handler = new MyHandler();tv = (TextView) findViewById(R.id.tv);btn_to = (Button) findViewById(R.id.btn_to);// 設定監聽器btn_to.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 設定共用變數mAPP.setHandler(handler);// 啟動另一個ActivityIntent intent = new Intent(MasterActivity.this,ToChangeViewActivity.class);startActivity(intent);}});}/** * 自己實現 Handler 處理訊息更新UI *  * @author mark */final class MyHandler extends Handler {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if(msg.what == CHANGED) { // 更新UItv.setText("changed after: I have be changed by Other Activity!");tv.setBackgroundColor(Color.BLUE);btn_to.setText("I have been changed!");btn_to.setBackgroundColor(Color.RED);}}}}

3. 自實現Application

對於Application可以參考sdk api文檔。在這裡,我就直接使用,不做解釋!

package mark.zhang;import mark.zhang.MasterActivity.MyHandler;import android.app.Application;/** * 自己實現Application,實現資料共用 *  * @author mark * */public class MyAPP extends Application {// 共用變數private MyHandler handler = null;// set方法public void setHandler(MyHandler handler) {this.handler = handler;}// get方法public MyHandler getHandler() {return handler;}}

4. 改變主Activity UI 的Activity

該 Activity 是 ToChangeViewActivity,Java、以及布局檔案 show.xml 代碼如下。

package mark.zhang;import mark.zhang.MasterActivity.MyHandler;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;public class ToChangeViewActivity extends Activity {private static final int CHANGED = 0x0010;private MyAPP mAPP = null;private MyHandler mHandler = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.show);mAPP = (MyAPP) getApplication();// 獲得該共用變數執行個體mHandler = mAPP.getHandler();findViewById(R.id.btn_chang).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 發送訊息mHandler.sendEmptyMessage(CHANGED);ToChangeViewActivity.this.finish();}});}}
<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  ><TextViewandroid:id="@+id/tv"  android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="hello,MasterActivity!"/> <Buttonandroid:id="@+id/btn_chang"  android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="change the MasterActivityView..."/> </LinearLayout>

5. 修改manifest.xml檔案
這裡主要注意兩點:

<1> 聲明 Application

<2> 註冊 ToChangeViewActivity

代碼,如下:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="mark.zhang"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="7" />    <application android:name=".MyAPP" android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".MasterActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <activity android:name=".ToChangeViewActivity"></activity>    </application></manifest>

6. 運行效果

點擊 " To OtherActivity",進入 ToChangeViewActivity 

再點擊“ change the MasterActivityView...”

改變效果

7. 最後思考

這裡只是兩個Activity之間互動,多個 Activity 之間需要考慮設定 launchMode 即 Activity 的載入模式,更多關於這方面的知識可以參考:

http://blog.csdn.net/androidbluetooth/article/details/6547670

http://download.csdn.net/source/3368975

本篇部落格源碼:http://download.csdn.net/source/3447670

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.