package com.example.wx;

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 android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private static final int DOWN_UPDATE = 1;
   
    private static final int DOWN_OVER = 2;
   
    private int progress;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgress = (ProgressBar)findViewById(R.id.pd);
        new updata().start();
    }

    class updata extends Thread{
     public void run() {
   try {
    URL url = new URL("http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk");
   
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.connect();
    int length = conn.getContentLength();
    InputStream is = conn.getInputStream();
    
    File file = new File("/sdcard/updatedemo/");
    if(!file.exists()){
     file.mkdir();
    }
    //String apkFile = "/sdcard/updatedemo/"+"test.apk";
    //File ApkFile = new File(apkFile);
    //FileOutputStream fos = new FileOutputStream(ApkFile);
    FileOutputStream fos = openFileOutput("test.apk", MODE_WORLD_READABLE);
    int count = 0;
    byte[] buffer = new byte[1024];
    int mylength = 0;
    Log.d("开始下载","开始下载");
    while ((mylength = is.read(buffer)) != -1) {
     fos.write(buffer,0,mylength);
    }
    fos.close();
    is.close();
    mHandler.sendEmptyMessage(DOWN_OVER);

   } catch (MalformedURLException e) {
    e.printStackTrace();
   } catch(IOException e){
    e.printStackTrace();
   }
   
  }
    }
    private void installApk(){
  File apkfile = new File(getFilesDir(), "test.apk");
  Log.d("文件路径", apkfile.toString());
        if (!apkfile.exists()) {
            //return;
            Log.d("存儲失敗", "存储失败");
            return;
        }   
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        this.startActivity(i);
 
 }
   
    private Handler mHandler = new Handler(){
     public void handleMessage(Message msg) {
      switch (msg.what) {
   case DOWN_UPDATE:
    
    break;
   case DOWN_OVER:
    mProgress.setVisibility(View.GONE);
    installApk();
    break;
   default:
    break;
   }
     };
    };
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}