冰浪

哥已不再年轻 - 坚定梦想,毕生追求!
posts - 85, comments - 90, trackbacks - 0, articles - 3
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Android中多个Activity间的数据共享

Posted on 2010-01-14 00:18 冰浪 阅读(3687) 评论(2)  编辑  收藏 所属分类: Android
在Android中使用Intent在两个Activity间传递数据时,只能是基本类型数据,或者是序列化对象。Intent是一种基于消息的进程内和进程间通信模型,当我们需要在我们应用程序内部,多个Activity间进行复杂数据对象共享交互时,使用Intent就显得很不方便。此时,我们就需要一种数据共享的机制来实现。当然,直接使用java语言中的静态变量是可以的,但在Android中有更为优雅的实现方式。

【转自:http://www.javaeye.com/topic/552758
【原文链接:http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables】

The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.

--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。

As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.
--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。

The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):
--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。

  1. class MyApp extends Application {   
  2.   
  3.   private String myState;   
  4.   
  5.   public String getState(){   
  6.     return myState;   
  7.   }   
  8.   public void setState(String s){   
  9.     myState = s;   
  10.   }   
  11. }   
  12.   
  13. class Blah extends Activity {   
  14.   
  15.   @Override  
  16.   public void onCreate(Bundle b){   
  17.     ...   
  18.     MyApp appState = ((MyApp)getApplicationContext());   
  19.     String state = appState.getState();   
  20.     ...   
  21.   }   
  22. }  

评论

# re: Android中多个Activity间的数据共享  回复  更多评论   

2010-09-02 10:02 by xhl
请问阁下:在AndroidManifest.xml中如何配置MyApp??

# re: Android中多个Activity间的数据共享  回复  更多评论   

2010-09-15 10:02 by HKMan
 在AndroidManifest.xml的application加个name属性就可以了,如下面所示:

  android:name=".MyApp" android:icon="@drawable/icon"
  android:label="@string/app_name">

只有注册用户登录后才能发表评论。


网站导航: