package com.wlwl.yiyuan; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DownloadManager; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.Window; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TabHost.TabSpec; import cn.jpush.android.api.JPushInterface; import com.wlwl.common.Config; import com.wlwl.common.FragmentHelp.OnBackListener; import com.wlwl.dal.D_News; import com.wlwl.enums.M_News; import com.wlwl.fragment.*; import com.wlwl.tools.ConvertX; import com.wlwl.tools.FileX; import com.wlwl.tools.URLX; import com.wlwl.tools.UtilX; @SuppressLint("NewApi") public class Index extends FragmentActivity implements OnBackListener { public static FragmentManager fm; String newVerName = "";//新版本名称 int newVerCode = -1;//新版本号 String newURL = "";//新版本下载地址 ProgressDialog pd = null; private static final String UPDATE_SERVERAPK = null; // 定义FragmentTabHost对象 private FragmentTabHost mTabHost; private RadioGroup mTabRg; private final Class[] fragments = { index.class, division.class, users.class,setting.class }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 去掉标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.index); initView(); boolean isNetWork = UtilX.isNetworkConnected(getApplicationContext()); if (isNetWork == true) { upadte(); } } public void upadte() { getServerVer(); } /** * 不更新版本 */ public void notNewVersionUpdate(){ int verCode = UtilX.getVerCode(this); String verName = UtilX.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("当前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append(" 已是最新版本,无需更新"); Dialog dialog = new AlertDialog.Builder(this) .setTitle("软件更新") .setMessage(sb.toString()) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub finish(); } }).create(); dialog.show(); } /** * 从服务器端获得版本号与版本名称 * * @return */ public boolean getServerVer() { try { try { new Thread(new Runnable() { public void run() { String url1 = Config.Url_UpdateApp; // 更新app地址 String aaa = URLX.GetUrl(url1); // 请求结果 mHandler.obtainMessage(2, aaa).sendToTarget(); } }).start(); } catch (Exception e) { // TODO: handle exception } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * 操作UI * */ private Handler mHandler = new Handler() { public void handleMessage(Message msg) {// 此方法在ui线程运行 switch (msg.what) { case 2: // 更新APP String s = msg.obj.toString(); if (ConvertX.IsNull(s) == false) { try { JSONObject jsonObject2 = new JSONObject(s); String state = jsonObject2.getString("state"); int rr = ConvertX.ToInt(state); if (rr == 200) { JSONArray jsonArray = new JSONObject(s) .getJSONArray("model"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObjectSon = (JSONObject) jsonArray .opt(i); String ver = jsonObjectSon.getString("ver"); String url= jsonObjectSon.getString("url"); String name = jsonObjectSon.getString("name"); newVerCode = ConvertX.ToInt( ver); newVerName = name; newURL = url; // FileX.Write_Log(newURL); int verCode = UtilX.getVerCode(Index.this); // 系统版本 Log.i("download_url",newURL); Log.i("download_name",name); Log.i("系统版本",verCode+""); Log.i("服务器版本",newVerCode+""); if (newVerCode > verCode) { doNewVersionUpdate();//更新版本 } else { } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { } break; } } }; private void DownLoadApp(String Url, String Name) { try { DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request down = new DownloadManager.Request( Uri.parse(Url)); // 设置允许使用的网络类型,这里是移动网络和wifi都可以 down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); // 是否显示在通知栏 down.setShowRunningNotification(true); // 是否显示下载界面 down.setVisibleInDownloadsUi(true); // 设置下载后文件存放的位置 down.setDestinationInExternalFilesDir(getApplication(), null, Name); // 表示允许MediaScanner扫描到这个文件,默认不允许。 //down.allowScanningByMediaScanner(); down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); down.setMimeType("application/vnd.android.package-archive"); // 设置为可被媒体扫描器找到 down.allowScanningByMediaScanner(); // 设置为可见和可管理 down.setVisibleInDownloadsUi(true); // 获取此次下载的ID // 注册广播接收器,当下载完成时自动安装 IntentFilter filter = new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE); down.setDestinationInExternalPublicDir("download", Name); // 将下载请求放入队列 long reference = manager.enqueue(down); Log.i("下载ID", reference + ""); } catch (Exception e) { Log.i("DownLoadApp(String Url , String Name)", e.getMessage()); } } /** * 更新版本 */ public void doNewVersionUpdate(){ int verCode = UtilX.getVerCode(this); String verName = UtilX.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("发现新版本"); sb.append(",是否更新"); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(sb.toString()) .setCancelable(false) .setPositiveButton("更新", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pd = new ProgressDialog(Index.this); pd.setTitle("正在下载"); pd.setMessage("请稍后。。。"); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); Toast.makeText(getApplication(), "正在下载请稍后.....", Toast.LENGTH_LONG).show(); DownLoadApp(newURL,newVerName); // downLoadFile(newURL); } }) .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } // 初始化Fragment(FragmentActivity中呼叫) public static void initFragment(android.app.Fragment f){ changeFragment(f, true); } private static void changeFragment(android.app.Fragment f, boolean init){ android.app.FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.realtabcontent, f); if(!init) ft.addToBackStack(null); ft.commit(); } private void initView() { mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); // 得到fragment的个数 int count = fragments.length; for (int i = 0; i < count; i++) { // 为每一个Tab按钮设置图标、文字和内容 TabSpec tabSpec = mTabHost.newTabSpec(i + "").setIndicator(i + ""); // 将Tab按钮添加进Tab选项卡中 mTabHost.addTab(tabSpec, fragments[i], null); } mTabRg = (RadioGroup) findViewById(R.id.tab_rg_menu); mTabRg.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.tab_rb_1: mTabHost.setCurrentTab(0); break; case R.id.tab_rb_2: mTabHost.setCurrentTab(1); break; case R.id.tab_rb_3: mTabHost.setCurrentTab(2); break; case R.id.tab_rb_4: mTabHost.setCurrentTab(3); break; default: break; } } }); mTabHost.setCurrentTab(0); } /** * 退出确认 * **/ public boolean onKeyDown(int keyCoder, KeyEvent event) { // if (keyCoder == KeyEvent.KEYCODE_BACK) { // // /* 2秒内点击两次返回退出程序 */ // if ((System.currentTimeMillis() - exitTime) > 2000) { // Toast.makeText(getApplicationContext(), "再按一次退出程序", // Toast.LENGTH_SHORT).show(); // exitTime = System.currentTimeMillis(); // } else { // finish(); // System.exit(0); // } // // } if (keyCoder == KeyEvent.KEYCODE_BACK) { int x = getFragmentManager().getBackStackEntryCount(); if (x == 0) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("你确定退出吗?") .setCancelable(false) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //finish(); //System.exit(0); /* * 回到桌面 * */ Intent home = new Intent(Intent.ACTION_MAIN); home.addCategory(Intent.CATEGORY_HOME); startActivity(home); } }) .setNegativeButton("返回", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); return true; } if (x == 1) { Toast.makeText(this, "x==1", Toast.LENGTH_SHORT).show(); } } return false; } @Override public void backEvent() { // TODO Auto-generated method stub } @Override protected void onResume() { Config.isForeground = true; super.onResume(); JPushInterface.onResume(this); } @Override protected void onPause() { Config.isForeground = false; super.onPause(); JPushInterface.onPause(this); } }
package com.wlwl.yiyuan;
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.UUID;
import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
import android.annotation.SuppressLint;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.DownloadManager;import android.app.FragmentManager;import android.app.ProgressDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.graphics.Bitmap;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentTabHost;import android.support.v4.app.FragmentTransaction;import android.util.Log;import android.view.KeyEvent;import android.view.Window;import android.widget.RadioGroup;import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;import android.widget.TabHost.TabSpec;import cn.jpush.android.api.JPushInterface;
import com.wlwl.common.Config;import com.wlwl.common.FragmentHelp.OnBackListener;import com.wlwl.dal.D_News;import com.wlwl.enums.M_News;import com.wlwl.fragment.*;import com.wlwl.tools.ConvertX;import com.wlwl.tools.FileX;import com.wlwl.tools.URLX;import com.wlwl.tools.UtilX;
@SuppressLint("NewApi")public class Index extends FragmentActivity implements OnBackListener { public static FragmentManager fm;String newVerName = "";//新版本名称 int newVerCode = -1;//新版本号 String newURL = "";//新版本下载地址 ProgressDialog pd = null;private static final String UPDATE_SERVERAPK = null;// 定义FragmentTabHost对象private FragmentTabHost mTabHost;private RadioGroup mTabRg;
private final Class[] fragments = { index.class, division.class, users.class,setting.class };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 去掉标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.index);initView();boolean isNetWork = UtilX.isNetworkConnected(getApplicationContext());if (isNetWork == true) {upadte();}}public void upadte() {getServerVer();} /** * 不更新版本 */ public void notNewVersionUpdate(){ int verCode = UtilX.getVerCode(this); String verName = UtilX.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("当前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append("
已是最新版本,无需更新"); Dialog dialog = new AlertDialog.Builder(this) .setTitle("软件更新") .setMessage(sb.toString()) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub finish(); } }).create(); dialog.show(); }
/** * 从服务器端获得版本号与版本名称 * * @return */public boolean getServerVer() {try {
try {new Thread(new Runnable() {public void run() {String url1 = Config.Url_UpdateApp; // 更新app地址String aaa = URLX.GetUrl(url1); // 请求结果mHandler.obtainMessage(2, aaa).sendToTarget();
}}).start();
} catch (Exception e) {// TODO: handle exception}
} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}return true;}
/** * 操作UI * */private Handler mHandler = new Handler() {public void handleMessage(Message msg) {// 此方法在ui线程运行switch (msg.what) {case 2: // 更新APPString s = msg.obj.toString();if (ConvertX.IsNull(s) == false) {
try {JSONObject jsonObject2 = new JSONObject(s);String state = jsonObject2.getString("state");int rr = ConvertX.ToInt(state);if (rr == 200) {JSONArray jsonArray = new JSONObject(s).getJSONArray("model");for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObjectSon = (JSONObject) jsonArray.opt(i);String ver = jsonObjectSon.getString("ver");String url= jsonObjectSon.getString("url");String name = jsonObjectSon.getString("name");newVerCode = ConvertX.ToInt( ver);newVerName = name; newURL = url; // FileX.Write_Log(newURL); int verCode = UtilX.getVerCode(Index.this); // 系统版本 Log.i("download_url",newURL); Log.i("download_name",name); Log.i("系统版本",verCode+""); Log.i("服务器版本",newVerCode+""); if (newVerCode > verCode) { doNewVersionUpdate();//更新版本} else {}}}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {}
break;}}};
private void DownLoadApp(String Url, String Name) {
try {DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request down = new DownloadManager.Request(Uri.parse(Url));
// 设置允许使用的网络类型,这里是移动网络和wifi都可以down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE| DownloadManager.Request.NETWORK_WIFI);// 是否显示在通知栏down.setShowRunningNotification(true);// 是否显示下载界面down.setVisibleInDownloadsUi(true);// 设置下载后文件存放的位置 down.setDestinationInExternalFilesDir(getApplication(), null, Name);
// 表示允许MediaScanner扫描到这个文件,默认不允许。//down.allowScanningByMediaScanner();
down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);down.setMimeType("application/vnd.android.package-archive");// 设置为可被媒体扫描器找到down.allowScanningByMediaScanner();// 设置为可见和可管理down.setVisibleInDownloadsUi(true);// 获取此次下载的ID
// 注册广播接收器,当下载完成时自动安装IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
down.setDestinationInExternalPublicDir("download", Name);// 将下载请求放入队列long reference = manager.enqueue(down);
Log.i("下载ID", reference + "");
} catch (Exception e) {Log.i("DownLoadApp(String Url , String Name)", e.getMessage());}
} /** * 更新版本 */ public void doNewVersionUpdate(){ int verCode = UtilX.getVerCode(this); String verName = UtilX.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("发现新版本"); sb.append(",是否更新"); AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage(sb.toString()).setCancelable(false).setPositiveButton("更新",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int id) { pd = new ProgressDialog(Index.this); pd.setTitle("正在下载"); pd.setMessage("请稍后。。。"); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); Toast.makeText(getApplication(), "正在下载请稍后.....",Toast.LENGTH_LONG).show(); DownLoadApp(newURL,newVerName); // downLoadFile(newURL);}}).setNegativeButton("暂不更新",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int id) {dialog.cancel();}});AlertDialog alert = builder.create();alert.show(); }
// 初始化Fragment(FragmentActivity中呼叫) public static void initFragment(android.app.Fragment f){ changeFragment(f, true); } private static void changeFragment(android.app.Fragment f, boolean init){ android.app.FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.realtabcontent, f); if(!init) ft.addToBackStack(null); ft.commit(); } private void initView() {mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);// 得到fragment的个数int count = fragments.length;for (int i = 0; i < count; i++) {// 为每一个Tab按钮设置图标、文字和内容TabSpec tabSpec = mTabHost.newTabSpec(i + "").setIndicator(i + "");// 将Tab按钮添加进Tab选项卡中mTabHost.addTab(tabSpec, fragments[i], null);}
mTabRg = (RadioGroup) findViewById(R.id.tab_rg_menu);mTabRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {switch (checkedId) {case R.id.tab_rb_1:mTabHost.setCurrentTab(0);break;case R.id.tab_rb_2:mTabHost.setCurrentTab(1);
break;case R.id.tab_rb_3:
mTabHost.setCurrentTab(2);break;case R.id.tab_rb_4:
mTabHost.setCurrentTab(3);break;
default:break;}}});
mTabHost.setCurrentTab(0);}/** * 退出确认 * **/public boolean onKeyDown(int keyCoder, KeyEvent event) {// if (keyCoder == KeyEvent.KEYCODE_BACK) {//// /* 2秒内点击两次返回退出程序 */// if ((System.currentTimeMillis() - exitTime) > 2000) {// Toast.makeText(getApplicationContext(), "再按一次退出程序",// Toast.LENGTH_SHORT).show();// exitTime = System.currentTimeMillis();// } else {// finish();// System.exit(0);// }//// }if (keyCoder == KeyEvent.KEYCODE_BACK) {int x = getFragmentManager().getBackStackEntryCount();if (x == 0) {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage("你确定退出吗?").setCancelable(false).setPositiveButton("确定",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int id) {//finish();//System.exit(0);/* * 回到桌面 * */Intent home = new Intent(Intent.ACTION_MAIN);
home.addCategory(Intent.CATEGORY_HOME);
startActivity(home); }}).setNegativeButton("返回",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int id) {dialog.cancel();}});AlertDialog alert = builder.create();alert.show();return true;}if (x == 1) {Toast.makeText(this, "x==1", Toast.LENGTH_SHORT).show();
}
}return false;
}
@Overridepublic void backEvent() {// TODO Auto-generated method stub}@Overrideprotected void onResume() {Config.isForeground = true;super.onResume();JPushInterface.onResume(this);}
@Overrideprotected void onPause() {Config.isForeground = false;super.onPause();JPushInterface.onPause(this);}}