两个不相关Activity之间的通信

同一个应用内两个不相关的activity 例如A进入B,B进入C,C进入D 或者A进入B,C进入D,那么A和D可以看做两个不相关的activity.
假如有这样一个需求,在D activity中按一个按钮,A activiy必须立即更新数据,那么可以的方法有哪些呢,我能想到的有以下几种:

第一种方式:

1 广播

这个就不细说了,Android的基础,百度一下就知道。

2 回调

如果是回调的话可以定义一个回调的管理类。
A实现回调接口,注册到管理类上,在D上面执行操作的时候,可以调用管理类的接口回调就可以了。
如:
a.接口是NotifyMessage,回调方法是sendMessage(String msg)
public interface NotifyMessage{
        public void sendMessage(String msg);
}
b.定义管理类NotifyMessageManager.
public class NotifyMessageManager{
        ......//可以采取单例
        private NotifyMessage listener;
        public void setNotifyMessage(NotifyMessage nm){
                listener = nm;
        }
        public void sendNotifyMessage(String msg){
                listener.sendMessage(msg);
        }
}
c.让A实现NotifyMessage接口,并注册到NotifyMessageManager上。
d.在D中调用NotifyMessageManager的sendNotifyMessage,这样就可以把数据发到A上面了。

3 intent

在android应用程序开发的时候,从一个activity启动另一个activity并传递一些数据到新的activity非常的简单,但是当您需要让后台运行的activity回到前台并传递一些数据可能就会存在一点点小问题。

首先,在默认情况下,当您通过intent启到一个activity的时候,就算已经存在一个相同的正在运行的activity,系统都会创建一个 新的activity实例并显示出来。为了不让activity实例化多次,我们需要通过在AndroidManifest.xml配置activity 的加载方式(launchMode)以实现单任务模式,如下所示:

<activity android:label="@string/app_name" android:launchmode="singleTask" android:name="Activity1">
</activity>

launchMode为singleTask的时候,通过intent启到一个activity,如果系统已经存在一个实例,系统就会将请求发送到这个实 例上,但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法,如下所示:

protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);//must store the new intent unless getIntent() will return the old one
  processExtraData();
}

不要忘记,系统可能会随时杀掉后台运行的activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:

复制代码
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  processExtraData();
}
 
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);//must store the new intent unless getIntent() will return the old one
  processExtraData()
}
 
private void processExtraData(){
  Intent intent = getIntent();
  //use the data received here
}


参考:

1 http://bbs.csdn.net/topics/390958417

2 http://www.cnblogs.com/longhs/p/4204017.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值