Ø在Activity之间数据传递中还有一种比较实用的方式,就是全局对象,实用J2EE的读者来说都知道Java Web的四个作用域,
这四个作用域从小到大分别是Page、Request、Session和Application,其中Application域在应用程序的任何地方都可以使用
和访问,除非是Web服务器停止,Android中的全局对象非常类似于Java Web中的Application域,除非是Android应用程序清
除内存,否则全局对象将一直可以访问。
Ø案例一
package com.android.myapp;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
private Button button;
private MyApp myApp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myApp = (MyApp)getApplication();
myApp.setName("jack");//修改之后的名称
Intent intent = new Intent(Main.this,OtherActivity.class);
startActivity(intent);
}
});
}
}
package com.android.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class OtherActivity extends Activity {
private MyApp myApp;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
textView = (TextView)this.findViewById(R.id.msg);
myApp = (MyApp)getApplication();
textView.setText("-appname-->>"+myApp.getName());
}
}
package com.android.myapp;
import android.app.Application;
public class MyApp extends Application {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setName("张三");
}
}