Android开发全局设置

2018-02-11 14:14:46来源:oschina作者:雪中无处寻人点击

分享
Android项目开发之Application

在开发项目时,往往有好多地方需要用到Context,Handler,Thread等,而且有时需要在界面初始化前做一些操作,这时候就需要自定义一个Application,请看参考代码:


package pengchao.p2pmoney.common;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
/**
* Created by Administrator on 2018/2/10.
*/
public class MyApplication extends Application {
public static Context context;
public static Handler handler;
public static int mainThreadId;
public static Thread mainThread = null;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
handler = new Handler();
mainThread = Thread.currentThread();
mainThreadId = android.os.Process.myTid();
}
}

在全局的Application中,静态变量不宜过多。


Android开发之AppManager

对于Andoroid开发人员来说,Activity是必须用到的,然而,有时根据业务需求大量的Activity的存在栈中很难管理,所以就需要AppManager来管理,参考代码如下:


package pengchao.p2pmoney.common;
import android.app.Activity;
import java.util.Stack;
/**
* Created by Administrator on 2018/2/10.
* 单例模式
* 统一app程序当中所有的acitivity栈管理
* 添加,删除指定,删除当前,删除所有,求栈大小
*/
public class AppManager {
private Stack mActivityStack =new Stack<>();
public static AppManager appManager = null;
private AppManager(){
}
public static AppManager getInstance(){
if (appManager == null){
appManager = new AppManager();
}
return appManager;
}
public void addActivity(Activity activity){
mActivityStack.add(activity);
}
//删除指定的activity
public void removeActivity(Activity activity){
for (int i = mActivityStack.size() - 1; i >= 0; i--) {
Activity activity1 = mActivityStack.get(i);
if(activity1.getClass().equals(activity.getClass())){
activity1.finish();
mActivityStack.remove(activity1);
break;
}
}
}
//删除当前的activity
public void removeCurrent(){
Activity lastElement = mActivityStack.lastElement();
lastElement.finish();
mActivityStack.remove(lastElement);
}
//移除所有的activity
public void removeAll(){
for (int i = mActivityStack.size() - 1; i >= 0; i--) {
Activity activity1 = mActivityStack.get(i);
activity1.finish();
mActivityStack.remove(activity1);
}
}
//查看当前栈中有多少activity
public int getSize(){
return mActivityStack.size();
}
}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台