android 用handler怎么把消息发送到指定的activity
2个回答
展开全部
1.在MyAPP中定义属性handler
package jason.com;
import jason.com.MasterActivity.MyHandler;
import android.app.Application;
/**
* 自己实现Application,实现数据共享
* @author jason
*/
public class MyAPP extends Application {
// 共享变量
private MyHandler handler = null;
// set方法
public void setHandler(MyHandler handler) {
this.handler = handler;
}
// get方法
public MyHandler getHandler() {
return handler;
}
}
2、在主activity 中给MyAPP的属性handler赋值
@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);
}
});
}
3、在另一个activity中获取MyAPP中handler进行传值
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();
}
});
}
package jason.com;
import jason.com.MasterActivity.MyHandler;
import android.app.Application;
/**
* 自己实现Application,实现数据共享
* @author jason
*/
public class MyAPP extends Application {
// 共享变量
private MyHandler handler = null;
// set方法
public void setHandler(MyHandler handler) {
this.handler = handler;
}
// get方法
public MyHandler getHandler() {
return handler;
}
}
2、在主activity 中给MyAPP的属性handler赋值
@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);
}
});
}
3、在另一个activity中获取MyAPP中handler进行传值
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();
}
});
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询