Handler: Activity 之间通过 Handler 通信

假设你已经明白下面的内容,那么这篇博客很适合您!

<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"
    >
	<TextView
		android: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;
	

	@Override
	public 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() {

			@Override
			public void onClick(View v) {
				// 设置共享变量
				mAPP.setHandler(handler);
				// 启动另一个Activity
				Intent intent = new Intent(MasterActivity.this,
						ToChangeViewActivity.class);
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 自己实现 Handler 处理消息更新UI
	 * 
	 * @author mark
	 */
	final class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == CHANGED) { // 更新UI
				tv.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;
	
	@Override
	protected 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() {
			
			@Override
			public 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"
  >
	<TextView
		android:id="@+id/tv"  
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" 
		android:text="hello,MasterActivity!"
		/> 
	
	<Button
		android: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



  • 9
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值