package com.zlkj.partynews;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.k.net.HttpUtil;
import com.zlkj.partynews.app.ActivityManager;
import com.zlkj.partynews.app.LoginManager;
import com.zlkj.partynews.app.ReLoginManager;
import com.zlkj.partynews.buisness.MainActivity;
import com.zlkj.partynews.model.entity.Result;
import com.zlkj.partynews.model.entity.my.UserEntity;
import com.zlkj.partynews.utils.JsonParser;
import com.zlkj.partynews.utils.LocalKeeperNew;
import com.zlkj.partynews.utils.SharedPreferenceManager;
import com.zlkj.partynews.utils.UrlUtils;
import com.zlkj.partynews.widget.LoadingDialog;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author zhang
* @date 2015
* @description
*/
public abstract class BaseActivity extends FragmentActivity {
TextView tvTitle = null;
RelativeLayout btnBack = null;
RelativeLayout rlTitle = null;
Button btnRight = null;
Button btnRight1 = null;
ImageView iv_right;
public NotificationManager mNotificationManager;
RelativeLayout rlContent = null;// 内容区
LinearLayout llLoading = null;// 加载圈
//
public ExecutorService pool = Executors.newCachedThreadPool();
private boolean isFinish = false;
protected List<HttpUtil> mHttpUtils = null;
// 基于 android 自带的asynctask
protected List<AsyncTask<Void, Void, Boolean>> backGourndTasklist = new ArrayList<AsyncTask<Void, Void, Boolean>>();
private boolean isFirstReq = true, isWait = false;// token
protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
backGourndTasklist.add(asyncTask.execute());
}
/**
* 不带参数的activity跳转
*
* @param activity
*/
public void toActivity(Class<? extends Activity> activity) {
Intent intent = new Intent(BaseActivity.this, activity);
startActivityForResult(intent, 0);
}
// 进入fragment
public void toFragment(Fragment fragment, int id) {
getSupportFragmentManager().beginTransaction().add(id, fragment).addToBackStack(null).commit();
}
/**
* 带参数的activity跳转
*
* @param activity
* @param bundle 参数集合, 在第二个activity 中可以通过 intent.getBundleExtra("map")
* 来获取bundle ,bundle类似于map ,也是key,value存储
*/
public void toActivityWithParam(Class<? extends Activity> activity, Bundle bundle) {
Intent intent = new Intent(BaseActivity.this, activity);
intent.putExtra("map", bundle);
startActivityForResult(intent, 0);
}
// 弹出loading
public void showLoading(String str) {
LoadingDialog.getInstance().show(getSupportFragmentManager(), str);
}
/**
* 更新loading提示内容
*
* @param str
*/
public void updateLoading(String str) {
if (this != null) {
LoadingDialog.getInstance().update(str);
}
}
// 关闭loading
public void cancelLoading() {
LoadingDialog.getInstance().dismissAllowingStateLoss();
}
protected void clearAsyncTaskBackGround() {
Iterator<AsyncTask<Void, Void, Boolean>> iterator = backGourndTasklist.iterator();
while (iterator.hasNext()) {
AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
if (asyncTask != null && !asyncTask.isCancelled()) {
asyncTask.cancel(true);
}
}
mHttpUtils.clear();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFinish = false;
mHttpUtils = new ArrayList<HttpUtil>();
ActivityManager.getInstance().onActivityCreate(this);
}
@Override
public void setContentView(int layoutResID) {
setTheme(SharedPreferenceManager.getNightMode() ? R.style.AppNight : R.style.AppLight);
View view = View.inflate(this, layoutResID, null);
LinearLayout llRoot = (LinearLayout) View.inflate(this, R.layout.activity_root_view, null);
rlTitle = (RelativeLayout) llRoot.findViewById(R.id.rlTitle);
btnBack = (RelativeLayout) llRoot.findViewById(R.id.rlBack);
tvTitle = (TextView) llRoot.findViewById(R.id.tvTitle);
iv_right = (ImageView) llRoot.findViewById(R.id.iv_right);
btnRight = (Button) llRoot.findViewById(R.id.btnRight);
btnRight1 = (Button) llRoot.findViewById(R.id.btnRight1);
rlContent = (RelativeLayout) llRoot.findViewById(R.id.rlContent);
llLoading = (LinearLayout) llRoot.findViewById(R.id.llLoading);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
rlContent.addView(view, lp);
// 标题返回事件
btnBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(MainActivity.RESULT_THEME);
finish();
}
});
super.setContentView(llRoot);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onDestroy() {
ActivityManager.getInstance().onActivityDestroy(this);
clearHttpUtils();
isFinish = true;
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
/**
* 显示标题
*
* @param str
*/
public void setTitle(String str) {
rlTitle.setVisibility(View.VISIBLE);
tvTitle.setText(str);
tvTitle.setTextColor(getResources().getColor(R.color.text_white));
}
/**
* 显示标题右侧按钮
*
* @param str
*/
public void setTitleRightBtn(String str, OnClickListener cl) {
btnRight.setVisibility(View.VISIBLE);
btnRight.setText(str);
btnRight.setOnClickListener(cl);
}
/**
* 隐藏标题右侧按钮
*/
public void hideTitleRightBtn() {
btnRight.setVisibility(View.GONE);
}
/**
* 显示标题右侧按钮
*
* @param str
*/
public void setTitleRightBtn(String str) {
btnRight.setText(str);
}
/**
* 获取标题右侧按钮显示文字
*/
public String getTitleRightBtn() {
return btnRight.getText().toString();
}
/**
* 显示标题右侧图片
*/
public void setTitleRightbitmapBtn(int bitmap, OnClickListener cl) {
btnRight.setVisibility(View.VISIBLE);
btnRight.setBackgroundResource(bitmap);
btnRight.setOnClickListener(cl);
}
/**
* 显示标题右侧图片
*/
public void setTitleRightDrawalbe(Drawable drawble, OnClickListener cl) {
rlTitle.setVisibility(View.VISIBLE);
iv_right.setVisibility(View.VISIBLE);
iv_right.setImageDrawable(drawble);
iv_right.setOnClickListener(cl);
}
/**
* 显示标题右侧按钮
*
* @param str
*/
public void setTitleRightBtn1(String str, OnClickListener cl) {
btnRight1.setText(str);
btnRight1.setOnClickListener(cl);
}
/**
* 隐藏返回按钮
*/
public void hideBackBtn() {
btnBack.setVisibility(View.GONE);
}
/**
* 隐藏返回按钮
*/
public void hideTitle() {
tvTitle.setVisibility(View.GONE);
}
/**
* 显示加载
*/
public void showLoadingInContent() {
llLoading.setVisibility(View.VISIBLE);
}
/**
* 隐藏加载
*/
public void hideLoadingInContent() {
llLoading.setVisibility(View.GONE);
}
//
// ****************************************************************
HttpUtil baseA = null;
/**
* 添加后台任务
*/
protected HttpUtil getHttpUtil() {
if (baseA == null)
baseA = new HttpUtil();
mHttpUtils.add(baseA);
return baseA;
}
List<String> httpMap = new ArrayList<String>();
/**
* 网络请求
*
* @param hl
* @param method
* @param url
* @param params
*/
public void request(final HttpUtil.HttpListenner hl, int method, final String url, String... params) {
request(hl, method, url, true, params);
}
/**
* 请求本地数据
*
* @param hl
* @param url
* @param params
*/
public void requestLocal(final HttpUtil.HttpListenner hl, final String url, final String... params) {
pool.execute(new Runnable() {
@Override
public void run() {
final String strLocal = getHttpUtil().requestLocalData(url, HttpUtil.POST, resetParam(params));
if (!TextUtils.isEmpty(strLocal)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (!isFinish)
hl.onLocalResult(strLocal);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
});
}
/**
* 网络请求
*
* @param hl
* @param method
* @param url
* @param isReConnection token过期时是否重新链接
* @param params
*/
public void request(final HttpUtil.HttpListenner hl, final int method, final String url,
final boolean isReConnection, final String... params) {
requestLocal(hl, url, params);
pool.execute(new Runnable() {
@Override
public void run() {
requestSyn(hl, method, url, isReConnection, params);
}
});
}
private void requestSyn(final HttpUtil.HttpListenner hl, final int method, final String url,
final boolean isReConnection, final String... params) {
synchronized (this) {
if (isWait) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (isFirstReq) {
isFirstReq = false;
isWait = true;
}
//
// isWait = true;
final String[] param = resetParam(params);
// **************为了保证token是最新的**********start***********************
int tokenIndex = -1;
if (param == null) {
return;
}
for (int j = 0; j < param.length; j++) {
if (TextUtils.equals("token", param[j])) {
tokenIndex = j + 1;
// Logger.e(this, "---------token---------------" + tokenIndex);
}
}
/////
if (tokenIndex >= 0) {
if (TextUtils.isEmpty(SharedPreferenceManager.getToken())) {
param[tokenIndex] = "fa468ecb376746f08568a5d442ef18da";
} else {
// param[tokenIndex] = SharedPreferenceManager.getToken();
param[tokenIndex] = SharedPreferenceManager.getToken();
}
}
////
// Logger.e(this, "---------token-in----------------" + param[tokenIndex]);
// ************************end********************************
// test start****
String pa = "";
int i = 0;
for (String string : param) {
if (i == 0) {
pa += "?" + string;
} else {
if (i % 2 == 0) {
pa += "&" + string;
} else {
pa += "=" + string;
}
}
i++;
}
// Logger.e(this, "url = " + url + pa);
// test end***********************
String strRem = getHttpUtil().requestData(url, method, param);
// Logger.e(this, "url = " + url + "\n con : " + strRem);
try {
Result res = JsonParser.parse(strRem, Result.class);
if (res != null) {
JSONObject jo = new JSONObject(strRem);
String data = jo.optString("data");
if ("TOKENEXPIRED".equals(data)) {
if (getUUID() && isReConnection) {
// 重新登陆
if (new ReLoginManager(BaseActivity.this).goLogin(null)) {
strRem = reConnection(method, url, param);
}
}
}
if ("NOPERMISSIONTOACCESSS".equals(data)) {
if (getUUID() && isReConnection) {
if (LoginManager.getInstance().isLogin()) {
// 重新登陆
if (new ReLoginManager(BaseActivity.this).goLogin(null)) {
strRem = reConnection(method, url, param);
}
} else {
// 重新连接~~~
strRem = reConnection(method, url, param);
}
}
}
}
if (isWait) {
try {
synchronized (this) {
notifyAll();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isWait = false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String conS = strRem;
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (!isFinish)
hl.onRemoteResult(conS);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
private String reConnection(final int method, final String url, final String[] param) {
String strRem;
int tokenIndex = -1;
for (int j = 0; j < param.length; j++) {
if (TextUtils.equals("token", param[j])) {
tokenIndex = j + 1;
}
}
if (tokenIndex >= 0)
param[tokenIndex] = SharedPreferenceManager.getToken();
// Logger.e(this, "reConnection ==url = " + url + "---" + param[tokenIndex]);
strRem = getHttpUtil().requestData(url, method, param);
return strRem;
}
private String[] resetParam(String... params) {
List<String> list = new ArrayList<String>();
boolean hasToken = false;
if (params == null) {
return null;
}
for (String string : params) {
list.add(string);
if (TextUtils.equals(string, "token")) {
hasToken = true;
}
}
if (!hasToken) {
list.add("token");
list.add("" + SharedPreferenceManager.getToken());
}
final String[] param = new String[list.size()];
for (int j = 0; j < list.size(); j++) {
param[j] = list.get(j);
}
return param;
}
private void notifyRequest() {
synchronized (this) {
try {
notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private boolean getUUID() {
// TODO Auto-generated method stub
String strJson = new HttpUtil().requestData(UrlUtils.URL_GET_TOKEN, HttpUtil.GET);
// Logger.e(this, "getUUID==== " + strJson);
try {
JSONObject jo = new JSONObject(strJson);
boolean success = jo.optBoolean("s");
if (success) {
String token = jo.optString("d");
SharedPreferenceManager.setToken(token);
SharedPreferenceManager.setTokenTime(System.currentTimeMillis());
UserEntity userEntity = LoginManager.getInstance().getUserEntity();
userEntity.setToken(token);
LocalKeeperNew.writeUserInfo(BaseActivity.this, userEntity);
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 取消后台任务
*/
public void clearHttpUtils() {
try {
for (HttpUtil task : mHttpUtils) {
if (task != null) {
task.cancle();
}
}
mHttpUtils.clear();
} catch (Exception e) {
}
}
public void toActivity(Class<? extends Activity> activity, Bundle bundle) {
Intent intent = new Intent();
if (bundle != null) {
intent.setClass(this, activity);
intent.putExtra("bundle", bundle);
}
startActivityForResult(intent, 0);
}
/**
* 隐藏软键盘
*/
public void hideInputMethod() {
View view = getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
BaseActivity
最新推荐文章于 2020-08-13 17:46:34 发布
268

被折叠的 条评论
为什么被折叠?



