android全局变量及多activity退出

两种方式:

1、  static类型数据,直接类名访问

2、  Application接口

 

package com.main; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.Application; /** * 全局变量工具类 * @author Administrator * */ public class ActivityManage extends Application { private List<Activity> mainActivity = new ArrayList<Activity>(); @Override public void onCreate() { super.onCreate(); } //以下实现完全退出多activity的应用界面 /** * * @return */ public List<Activity> MainActivity () { return mainActivity ; } public void addActivity(Activity act) { mainActivity.add(act); } public void finishAll() { System.out.println("activity num:" + mainActivity.size()); for(int index = 0; index < mainActivity.size(); index ++) { Activity act = (Activity)mainActivity.get(index); act.finish(); } mainActivity.clear(); } }

 必须在

AndroidManifest.xml中添加我们自己的Application

 

 

Eg:

<application

        android:icon="@drawable/ic_launcher" 以前系统的

        android:label="@string/app_name"    以前系统的

       android:name=".ActivityManage">    自己的Application

利用Application操作全局变量:

ActivityManage actM = (ActivityManage)getApplicationContext();

String strTemp = (editID.getText()).toString();//"01234567890";//new String((String) textID.getText());

 actM.setDeviceID(strTemp);

 

 

利用Application接口实现退出多activity程序:

退出多activity应用程序实现:

每一个新的activity进入时,加上如下代码:

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //

        ActivityManage actM = (ActivityManage)getApplicationContext();

        actM.addActivity(this);

        strDeviceID = actM.getDeviceID();

 

退出时:

ActivityManage actM = (ActivityManage)getApplicationContext(); actM.finishAll();

 

监听按键事件:

 

/** * 监听返回按键 */ public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){ //code........ //System.exit(0); ActivityManage actM = ActivityManage)getApplicationContext(); actM.finishAll(); } return false; }

 注:需要在

AndroidMainfest.xml文件中在application标签添加:

 

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:name=".ActivityManage" >

 

 ActivityManage中:

public void finishAll()

{

System.out.println("activitynum:"+mainActivity.size());

for(intindex=0;index<mainActivity.size();index++)

{

Activityact=(Activity)mainActivity.get(index);

act.finish();

}

mainActivity.clear();

if(so!=null)

{

so.socketDestory();

}

if(remoteDB!=null)

{

remoteDB.closeDB();

}

}

相关推荐