package com.jqyd.manager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.TagAliasCallback; import com.jqyd.app.MyApp; import com.jqyd.app.ShareMethod; import com.jqyd.pub.SHA1; import com.jqyd.shareInterface.CheckState_interface; import com.jqyd.shareInterface.ConnectStateService; import com.jqyd.shareInterface.DeleteRecordReceiver; import com.jqyd.shareInterface.Optdb_interfce; import com.jqyd.shareInterface.Optsharepre_interface; import com.jqyd.shareInterface.SystemInfo; import com.jqyd.shareInterface.UpdataToServer; public class Login extends Activity { private EditText loginNameEt; private EditText pwdEt; private Button loginBt; private CheckBox remPwdCb; private TextView showInfo; private LinearLayout load_lin; private LinearLayout content_lin; private Optsharepre_interface share_obj = null; private Optdb_interfce db = null; private String loginNameStr; private String pwdStr; private ProgressDialog pBar; private File sdPath; private String appName; private MyApp myApp; private String upContent = ""; private String sign = "0";// 记号:0、不必须升级1、必须升级 private ShareMethod shareMethd = null; /** * 文件一共的大小 */ long length = 0; /** * 已经下载的大小 */ int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login); myApp = (MyApp) this.getApplication(); share_obj = new Optsharepre_interface(Login.this); isfirst(); initView(); DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); int width = metric.widthPixels; // 屏幕宽度(像素) int height = metric.heightPixels; // 屏幕高度(像素) Log.i("LOGIN", "宽度:" + width + "," + height); shareMethd = new ShareMethod(Login.this); } @Override protected void onDestroy() { // TODO Auto-generated method stub Log.e("Login", "onDestroy"); super.onDestroy(); } private void initView() { loginNameEt = (EditText) findViewById(R.id.loginNameEt); pwdEt = (EditText) findViewById(R.id.pwdEt); loginBt = (Button) findViewById(R.id.loginBt); remPwdCb = (CheckBox) findViewById(R.id.remPwdCb); showInfo = (TextView) this.findViewById(R.id.load); load_lin = (LinearLayout) Login.this.findViewById(R.id.load_begin); content_lin = (LinearLayout) Login.this.findViewById(R.id.content); loginBt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub loginNameStr = loginNameEt.getText().toString(); pwdStr = pwdEt.getText().toString(); if ("".equals(loginNameStr) || "".equals(pwdStr)) { new AlertDialog.Builder(Login.this).setTitle("提示") .setMessage("用户名或密码为空!") .setPositiveButton("确定", null).show(); } else { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(pwdEt.getWindowToken(), 0); db = new Optdb_interfce(Login.this); String timeNode = "19000101"; // 获得时间节点,判断是否首次登录 ArrayList<Object> list = new ArrayList<Object>(); try { list = db.searchFromDb("DATA_UPDATES"); // 关闭数据库 db.close_SqlDb(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("初次登陆*****"); } if (list.size() > 0) { timeNode = ""; for (int i = 0; i < list.size(); i++) { timeNode += list.get(i) + "#"; } timeNode = timeNode.substring(0, timeNode.length() - 1); } // 获得功能角色 String values = share_obj.getDataFromPres("LOGIN"); String vals[] = values.split("#"); String updatetag; if (timeNode.equals("19000101")) { showInfo.setText("正在加载数据,请耐心等待……"); updatetag = "0"; } else { showInfo.setText("正在登录,请稍候……"); updatetag = "1"; } TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imsi = tm.getSubscriberId(); // 取出现在的IMSI号码 if(imsi==null){ imsi="000000000000000"; } Log.e("imsi", imsi); String vercode = new SystemInfo(Login.this) .getVersionInfo(); //"460003455528987" //460006800277917 // loginNameStr = "18638679800";//组长 // pwdStr = "lgf123456";//组长 // imsi = "685B35834316";//组长 // imsi = "460030261791127"; shareMethd.recordLog("开始登陆,版本号是:"+vercode); new LoginThread(loginNameStr, pwdStr, imsi, vals[0], timeNode, myApp.getVersion(), vercode,updatetag).start(); } } }); Log.i("LOGIN", "配置文件:" + share_obj.getDataFromPres("REGSIM")); loginNameEt.setText(share_obj.getDataFromPres("REGSIM")); // 判断是否勾选记忆密码 String isRew = share_obj.getDataFromPres("RPWD"); if (isRew.equals("1")) { remPwdCb.setChecked(true); pwdEt.setText(share_obj.getDataFromPres("PWD")); } else { remPwdCb.setChecked(false); } } /** * 登录线程 * * @author Administrator * */ class LoginThread extends Thread { String username; String password; String imsi; String gnjs; String timeNode; String version; String vercode; String updatetag; public LoginThread(String username, String password, String imsi, String gnjs, String timeNode, String version, String vercode,String updatetag) { this.username = username; this.password = password; this.imsi = imsi; this.gnjs = gnjs; this.timeNode = timeNode; this.version = version; this.vercode = vercode; this.updatetag = updatetag; } @Override public void run() { // TODO Auto-generated method stub super.run(); Looper.prepare(); Message message1 = new Message(); message1.what = 1; myHander.sendMessage(message1); UpdataToServer server = new UpdataToServer(Login.this); Log.e("imsi=+",imsi); String loginResult = server.loginToServer(username, password, imsi, gnjs, timeNode, version, vercode,updatetag); shareMethd.recordLog("登陆结果:"+loginResult); Message message2 = new Message(); Bundle bundle = new Bundle(); String rets[] = loginResult.split("#"); System.out .println("登录结果测试---------------------------------------------" + rets[0]); Log.e("loginResult-----------------", loginResult); if (rets[0].equals("-999")) {// 登录成功,且有版本更新 shareMethd.recordLog("登陆成功,且有版本更新"); share_obj.editPres("REGSIM", username); share_obj.editPres("password", password); SHA1 sha1 =new SHA1(); String sha1str = sha1.getDigestOfString((username+password).getBytes()); share_obj.editPres("sha1", sha1str); // 判断是否记忆密码 if (remPwdCb.isChecked()) { share_obj.editPres("RPWD", "1"); } else { share_obj.editPres("RPWD", "0"); } String res[] = loginResult.split("#"); upContent = res[4]; sign = res[5]; String mess = ""; if (sign.equals("0")) { mess = "下次再说"; } else { mess = "退出"; } checkVersion(res[3], mess);// 执行版本更新 } else if (rets[0].equals("0")) {// 登录成功 shareMethd.recordLog("登陆成功"); // 判断是否记忆密码 if (remPwdCb.isChecked()) { share_obj.editPres("RPWD", "1"); } else { share_obj.editPres("RPWD", "0"); } share_obj.editPres("REGSIM", username); share_obj.editPres("password", password); SHA1 sha1 =new SHA1(); String sha1str = sha1.getDigestOfString((username+password).getBytes()); share_obj.editPres("sha1", sha1str); bundle.putString("msg", "登录成功,正在进入……"); message2.setData(bundle); message2.what = 2; } else { bundle.putString("msg", rets[1]); message2.what = 3; } Set<String> set = new HashSet<String>(); set.add(share_obj.getDataFromPres("COSIM")); JPushInterface.setAliasAndTags(getApplicationContext(), username, set,new TagAliasCallback() { @Override public void gotResult(int arg0, String arg1, Set<String> arg2) { // TODO Auto-generated method stub switch (arg0) { case 0: shareMethd.recordLog("绑定成功"); break; case -996: shareMethd.recordLog("网络连接断开"); break; case -994: shareMethd.recordLog("网络连接超时"); break; case -997: shareMethd.recordLog("注册失败(一般是由于没有网络造成的)"); break; case 1008: shareMethd.recordLog("AppKey非法"); break; case 1005: shareMethd.recordLog("包名和AppKey 不匹配"); break; default: break; } } }); message2.setData(bundle); myHander.sendMessage(message2); Looper.loop(); } } private Boolean offLogin(String username,String password ){ SHA1 sha1 = new SHA1(); String sha1str = sha1.getDigestOfString((username+password).getBytes()); if(share_obj.getDataFromPres("sha1").equals(sha1str)){ return true; }else{ return false; } } Handler myHander = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 1: // 正在执行 load_lin.setVisibility(LinearLayout.VISIBLE); content_lin.setVisibility(LinearLayout.GONE); break; case 2: // 成功 Bundle bundle = msg.getData(); showInfo.setText(bundle.getString("msg")); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); // 10分钟之后,删除30天之前的日志记录 deleteRecord(); myApp.setIslogin(true); finish(); break; case 3: // 失败 load_lin.setVisibility(LinearLayout.GONE); content_lin.setVisibility(LinearLayout.VISIBLE); Bundle bundle2 = msg.getData(); if(bundle2.getString("msg").equals("数据更新出现异常!")){ load_lin.setVisibility(LinearLayout.VISIBLE); content_lin.setVisibility(LinearLayout.GONE); String info =bundle2.getString("msg"); //dataCleanDialog(info.substring(0, info.length()-1)); showInfo.setText("数据更新出现异常,数据清理中……"); cleanData();//数据清理 InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(pwdEt.getWindowToken(), 0); db = new Optdb_interfce(Login.this); String timeNode = "19000101"; String values = share_obj.getDataFromPres("LOGIN"); String vals[] = values.split("#"); showInfo.setText("正在加载数据,请耐心等待……"); TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imsi = tm.getSubscriberId(); // 取出现在的IMSI号码 if(imsi==null){ imsi="000000000000000"; } Log.e("imsi", imsi); String vercode = new SystemInfo(Login.this) .getVersionInfo(); new LoginThread(loginNameStr, pwdStr, imsi, vals[0], timeNode, myApp.getVersion(), vercode,"0").start(); }else if(bundle2.getString("msg").equals("请检查网络连接是否正常!")){ Toast.makeText(Login.this, bundle2.getString("msg"), Toast.LENGTH_SHORT).show(); if(!share_obj.getDataFromPres("password").equals("0")){ loginDialog();//离线登录 } }else{ Toast.makeText(Login.this, bundle2.getString("msg"), Toast.LENGTH_SHORT).show(); } break; } } }; /** * 数据清理 * */ private void dataCleanDialog(String msg) { AlertDialog.Builder builder = new Builder(Login.this); builder.setMessage(msg+",是否进行数据清除"); builder.setPositiveButton("是", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { cleanData(); } catch (Exception e) { // TODO: handle exception } dialog.cancel(); } }); builder.setNegativeButton("否", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); builder.create().show(); } /** * 离线登录 * */ private void loginDialog() { AlertDialog.Builder builder = new Builder(Login.this); builder.setMessage("是否进入离线登录"); builder.setPositiveButton("是", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if(offLogin(loginNameStr, pwdStr)){ Intent in = new Intent(Login.this, MainActivity.class); startActivity(in); Toast.makeText(Login.this, "离线登录成功", Toast.LENGTH_SHORT).show(); Login.this.finish(); }else{ Toast.makeText(Login.this, "用户名或密码错误", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("否", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); builder.create().show(); } /** * 登录结果显示 * * @param message */ public void showToast(String message) { new AlertDialog.Builder(this).setTitle("提示").setMessage(message) .setPositiveButton("确定", null).show(); } /** * 版本升级代码 */ public void checkVersion(final String url, final String mess) { System.out.println("版本升级---------------"); String[] upContents = upContent.split(","); String strCont = "新版本更新内容:"; for (int i = 0; i < upContents.length; i++) { strCont += "\n" + upContents[i]; } AlertDialog.Builder dialog = new AlertDialog.Builder(Login.this); dialog.setTitle("版本升级") .setMessage(strCont) // 设置内容 .setPositiveButton("现在升级",// 设置确定按钮 new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { downFile(url); } }) .setNegativeButton(mess, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); if (sign.equals("1")) { finish();// 退出系统 } else { Message message2 = new Message(); Bundle bundle = new Bundle(); bundle.putString("msg", "登录成功,正在进入……"); message2.setData(bundle); message2.what = 2; message2.setData(bundle); myHander.sendMessage(message2); } } }); // 显示对话框 dialog.create().show(); } /** * 下载安装文件 * * @param url */ public void downFile(final String url) { Message m = new Message(); m.what = 1; handler.sendMessage(m); appName = url.substring(url.lastIndexOf("/"), url.length()); if ((Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {// SD卡 sdPath = Environment.getExternalStorageDirectory(); } else {// 内存 sdPath = Login.this.getFilesDir(); } new Thread() { public void run() { HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url System.out.println("url---------" + url); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; length = entity.getContentLength(); pBar.setMax((int) length); if (is != null) { File file = new File(sdPath, appName); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); count += ch; Message m = new Message(); m.what = 2; handler.sendMessage(m); } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } down(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); String message = ""; boolean netState = false; // 检测SIM卡状况 CheckState_interface checkObj = new CheckState_interface(Login.this); int simResult = checkObj.checkSimState(); if (simResult == 1) { message = "SIM卡未找到,请重新装入SIM卡,或者更换新卡!"; } // 检测网络状况 netState = checkObj.checkConnection(); Log.i("netcheck", netState + ""); if (!message.equals("")) { Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show(); } if (!netState) { Toast.makeText(Login.this, "检查到没有可用的网络,请打开网络连接!", Toast.LENGTH_LONG) .show(); } } @Override public void finish() { // TODO Auto-generated method stub super.finish(); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: pBar = new ProgressDialog(Login.this); pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pBar.setMessage("正在下载更新"); pBar.setCancelable(false); pBar.show(); break; case 2: pBar.setProgress(count); break; case 3: pBar.dismiss(); break; } } }; /** * 下载完后取消progressBar效果 * * @view plaincopy to clipboardprint? */ public void down() { handler.post(new Runnable() { public void run() { Message m = new Message(); m.what = 3; handler.sendMessage(m); // 进行更新操作 update(); } }); } /** * 启动系统更新 * */ public void update() { if ((Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED))) {// SD卡 try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.fromFile(new File(sdPath.getPath() + "/" + appName)), "application/vnd.android.package-archive"); startActivity(intent); this.finish(); } catch (Exception e) { e.printStackTrace(); } } else {// 内存 if(changerMode(new File(sdPath.getPath() + "/" + appName))){ try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.fromFile(new File(sdPath.getPath() + "/" + appName)), "application/vnd.android.package-archive"); startActivity(intent); this.finish(); } catch (Exception e) { e.printStackTrace(); } } } } /** * * Description: 10分钟之后删除30天以前的日志 Title: deleteRecord void */ private void deleteRecord() { // 操作:发送一个广播,广播接收后Toast提示定时操作完成 Intent intent = new Intent(Login.this, DeleteRecordReceiver.class); intent.setAction("com.jqyd.manager.DeleteRecordReceiver"); PendingIntent sender = PendingIntent.getBroadcast(Login.this, 0, intent, 0); // 设定一个五秒后的时间 Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.MINUTE, 10); AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); Log.d("log", "删除日志时间到了"); shareMethd.recordLog("删除日志时间到了"); } /** * * Description: 修改文件权限 * Title: changerMode * @param file * @return * boolean */ public boolean changerMode(File file){ try { Process p = Runtime.getRuntime().exec("chmod 755 " + file); int status = p.waitFor(); if (status == 0) { // Toast.makeText(context, "权限修改成功", Toast.LENGTH_SHORT).show(); return true; }else{ // Toast.makeText(context, "权限修改失败", Toast.LENGTH_SHORT).show(); return false; } } catch (IOException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } } private void isfirst(){ if(share_obj.getDataFromPres("isfirst").equals("0")){ Optdb_interfce opt = new Optdb_interfce(this); opt.deleteFromDb("ALL"); opt.close_SqlDb(); File file =new File("/data/data/" + this.getPackageName() + "/shared_prefs"); File file2 =this.getCacheDir(); // if (file != null && file.exists() && file.isDirectory()) { // for (File item : file.listFiles()) { // Log.e("shared", "----------"); // item.delete(); // } // } share_obj.SharedClear(); if (file2 != null && file2.exists() && file2.isDirectory()) { for (File item : file2.listFiles()) { item.delete(); } } share_obj.editPres("isfirst", "1"); } } private void cleanData(){ Optdb_interfce opt = new Optdb_interfce(this); opt.deleteFromDb("ALL"); opt.close_SqlDb(); File file =new File("/data/data/" + this.getPackageName() + "/shared_prefs"); File file2 =this.getCacheDir(); share_obj.SharedClear(); if (file2 != null && file2.exists() && file2.isDirectory()) { for (File item : file2.listFiles()) { item.delete(); } } Toast.makeText(Login.this, "数据清理成功", Toast.LENGTH_SHORT).show(); } }