zoukankan      html  css  js  c++  java
  • 两个正在运行的activity之间的通信

    在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
    }
  • 相关阅读:
    Vector(同步)和ArrayList(异步)异同
    集合框架(1)
    如何优化limit
    Mysql5大引擎之间的区别和优劣之分
    差分约束 poj 3169
    最大权森林 poj 3723
    次短路 poj 3255
    P1604 B进制星球 (高精度进制计算器)
    最小生成树入门 kruskal和堆优化的prim
    并查集入门 POJ 1182(带权并查集)
  • 原文地址:https://www.cnblogs.com/longhs/p/4204017.html
Copyright © 2011-2022 走看看