1 public classMainActivity extends Activity {2 3 private String currentFilePath = "", currentTempFilePath = "", strURL = "",4 fileEx = "", fileNa = "";5 File file2 = new File(Environment.getExternalStorageDirectory()+"");6 @SuppressLint("SetJavaScriptEnabled")7 @Override8 public voidonCreate(Bundle savedInstanceState) {9 super.onCreate(savedInstanceState);10 setContentView(R.layout.activity_main);11 fragmentLayout =(View) findViewById(R.id.fragment);12 gotoButton =(Button) findViewById(R.id.goto_button);13 gotoButton.setOnClickListener(gotoListener);14 }15 16 OnClickListener gotoListener = newOnClickListener() {17 18 @Override19 public voidonClick(View v) {20 21 //String webUrl = "http://fancy.189.cn/portal/getclientapk";22 //Uri uri = Uri.parse(webUrl);23 //Intent intent = new Intent(Intent.ACTION_VIEW, uri);24 //startActivity(intent);25 //finish();
26 strURL = "http://fancy.189.cn/portal/getclientapk";27 /*取得欲安装程序名称*/
28 fileEx = "telecom_mdesk";29 fileNa = ".apk";30 getFile(strURL);31 }32 };33 34 /*处理下载URL文件自定义函数*/
35 private voidgetFile(final String strPath) {36 try{37 if(strPath.equals(currentFilePath)) {38 getDataSource(strPath);39 }40 currentFilePath =strPath;41 Runnable r = newRunnable() {42 public voidrun() {43 try{44 getDataSource(strPath);45 } catch(Exception e) {46 Log.e("TAG", e.getMessage(), e);47 Log.e("TAG", "------>");48 }49 }50 };51 newThread(r).start();52 } catch(Exception e) {53 e.printStackTrace();54 }55 }56 57 /*取得远程文件*/
58 private voidgetDataSource(String strPath) throws Exception {59 //if (!URLUtil.isNetworkUrl(strPath))60 //mTextView01.setText("错误的URL");61 //else62 //{
63 /*取得URL*/
64 URL myURL = newURL(strPath);65 /*创建连接*/
66 //URLConnection conn = myURL.openConnection();
67 HttpURLConnection conn =(HttpURLConnection) myURL.openConnection();68 conn.setRequestMethod("POST");69 //is = connection.getInputStream();70 //conn.connect();
71 /*InputStream 下载文件*/
72 InputStream is =conn.getInputStream();73 if (is == null)74 throw new RuntimeException("stream is null");75 76 /*创建临时文件*/
77 File myTempFile =File.createTempFile(fileEx, fileNa, file2);78 /*取得临时文件路径*/
79 currentTempFilePath =myTempFile.getAbsolutePath();80 /*将文件写入暂存盘*/
81 FileOutputStream fos = newFileOutputStream(myTempFile);82 byte buf[] = new byte[128];83 do{84 int numread = is.read(buf);85 if (numread <= 0)86 break;87 88 Log.v("TAG", "下载中---");89 90 fos.write(buf, 0, numread);91 } while (true);92 93 /*打开文件进行安装*/
94 openFile(myTempFile);95 try{96 is.close();97 } catch(Exception ex) {98 Log.e("TAG", "error:" +ex.getMessage(), ex);99 }100 //}
101 }102 103 /**104 * 在手机上打开文件105 */
106 private voidopenFile(File f) {107 Intent intent = newIntent();108 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);109 intent.setAction(android.content.Intent.ACTION_VIEW);110 111 /*调用getMIMEType()来取得MimeType*/
112 String type = "application/vnd.android.package-archive";113 /*设置intent的file与MimeType*/
114 intent.setDataAndType(Uri.fromFile(f), type);115 startActivity(intent);116 }117 }