转自:http://blog.csdn.net/liangguo03/article/details/6860179
有时候我们需要在Activity之外的类中修改Activity中的数据或是UI, 或者是要在自定义的类中要修改其它类中的值。这时候就变的很麻烦!这时候我们就需要一个全局的容器,来存放要共享的数据,就像J2EE中的Session。 当然,Android设计者肯定也考虑到了这一点。进入正题-----> Application(注: 本节只简单介绍一下使用方法,相信天才的码农们举一反三)
使用方法:
第一、实现自己的Applicaiton
- public class ApplicationContext extends Application {
- public static final int FLUSH_MAIN_ACTIVITY=1;
- private Handler main;
- public void setMainHandler(Handler handler){
- main=handler;
- }
- public void flushMain(){
- main.sendEmptyMessage(FLUSH_MAIN_ACTIVITY);
- }
- }
第二、在Activity中定义Handler ,并注册Handler
- package com.sequel.text;
- import android.app.Activity;
- import android.app.Application;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- public class MainActivity extends Activity {
- private int count = 0;
- /** Called when the activity is first created. */
- //定义Handler,
- Handler flushHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case ApplicationContext.FLUSH_MAIN_ACTIVITY:
- //在这可进行想要的操作
- operat();
- break;
- default:
- break;
- }
- super.handleMessage(msg);
- }
- };
- private ApplicationContext appC;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- appC = (ApplicationContext) getApplication();
- //注册Handler
- appC.setMainHandler(flushHandler);
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- startActivity(new Intent(MainActivity.this,SecondActivity.class));//启动另一个Activity
- }
- public void operat(){
- //.....
- System.out.println(count++);
- }
- }
第三、调用方法----在SecondActivity中进行操作
- import android.app.Activity;
- import android.app.Application;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class SecondActivity extends Activity {
- /** Called when the activity is first created.*/
- private ApplicationContext appC;
- private Button button;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.second);
- button = (Button) findViewById(R.id.requestButton);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //这就是调用方法
- appC.flushMain();
- }
- });
- appC = (ApplicationContext) getApplication();
- }
- }
第四、千万不要以为这就完事大吉了! 一定要在AndroidManifest.xml中注册你自己定义的Application
- <application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ApplicationContext">