Android进阶篇-软件下载及安装

 

private static final String TAG = MainActivity.class.getSimpleName();
    
    private Button button ;
    private Notification notification;
    private NotificationManager manager;
    private String softwarePath;
    
    private int downedFileLength=0;  
    private int fileLength;
    private static final String softwareName = "新浪微博";
    private static final int NOTIFICATION_ID = 0x12;
    private String path = "http://3g.sina.com.cn/tv/soft/weibo/com.sina.weibo-vn2.4.5-signed-final.apk";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        softwareDownload();
    }
    
    //软件下载
    private void softwareDownload(){
        notification = new Notification();
        notification.icon = R.drawable.ic_launcher;//通知栏的现实图片
        notification.tickerText = softwareName;//弹出通知栏
        notification.contentView = new RemoteViews(getApplication().getPackageName(), R.layout.custom_dialog);//设置通知栏里面的样式
        notification.contentView.setProgressBar(R.id.proBar_downBar, fileLength, 0, false);
        notification.contentView.setTextViewText(R.id.txt_downTitle, softwareName+"    进度" + 0+ "%");
        notification.contentIntent = PendingIntent.getActivity(this, 0,    new Intent(this, MainActivity.class), 0);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, notification);
        
        //开启新线程进行软件下载
        new Thread(){
            
            public void run(){
                try {
                    softwarePath = downLoadApk(path, softwareName+".apk",downLoadHandler);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }.start();
    }
    
    //利用handler进行下载过程的监控
    private Handler downLoadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg)  
            {  
            if (!Thread.currentThread().isInterrupted()) {  
                switch (msg.what) {  
                case 0:  
                    Log.i(TAG,"----------开始下载-----------------");
                    MainActivity.this.fileLength = getInteger(msg.obj);
                    notification.contentView.setProgressBar(
                            R.id.proBar_downBar, downedFileLength, msg.arg1, false);
                    break;  
                case 1:  
                    Log.i(TAG,"----------下载中-----------------");
                    MainActivity.this.downedFileLength = getInteger(msg.obj);
                    notification.contentView.setProgressBar(
                            R.id.proBar_downBar,fileLength, downedFileLength, false);
                    int x=downedFileLength*100/fileLength; 
                    notification.contentView.setTextViewText(R.id.txt_downTitle, softwareName+"    进度"+x+"%");
                    manager.notify(NOTIFICATION_ID, notification);
                    break;  
                case 2:  
                    Log.i(TAG,"----------下载完成-----------------");
                    manager.cancel(NOTIFICATION_ID);
                    Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show(); 
                    MainActivity.this.installSoftware();
                    break;  
                default:  
                    break;  
                }  
            }    
          }
    };
    
    //安装软件
    private void installSoftware(){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(softwarePath)), "application/vnd.android.package-archive");
        startActivity(intent);
    }
    
    /**下载APK文件
     * 
     * @param urlStr Url地址
     * @param apkName apk名字
     * @param handler handler
     */
    public String downLoadApk(String urlStr, String apkName,Handler handler)
            throws Exception {
        HttpGet get = new HttpGet(urlStr);
        HttpResponse response = null;
        response = getDefaultHttpClient(7000).execute(get);
        if (response == null || response.getStatusLine().getStatusCode() != 200)
            throw new UnsupportedOperationException();
        Header header = response.getFirstHeader("Content-Length");
        header.getValue();
        
        /**SD卡存储的目录*/
        String apkMir = "";
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
            apkMir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/app/";
        }else{
            apkMir = "/data/app/";
        }
        File dirFile = new File(apkMir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        File apkFile = new File(apkMir + apkName);
        if (!apkFile.exists())
            apkFile.createNewFile();
        
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec("chmod 666 "+ apkFile.getAbsolutePath());
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        FileOutputStream fis = new FileOutputStream(apkFile);
        InputStream is = response.getEntity().getContent();
        
        /**通过发送message到handler来进行下载过程的监控*/
         long fileSize=response.getEntity().getContentLength();
        Message message0 =new Message();
        message0.what=0;
        message0.obj=fileSize;
        handler.sendMessage(message0);
        
        byte[] buf = new byte[1024];
        int length = -1;
        int allLength=0;
        int len=0;
        while ((length = is.read(buf)) != -1) {
            fis.write(buf, 0, length);
            len+=length;
            allLength+=length;
            if(len>fileSize/80){
                Message message1 =new Message();
                message1.what=1;
                message1.obj=allLength;
                handler.sendMessage(message1);
                len=0;
            }
        }
        fis.flush();
        
        Message message2 =new Message();
        message2.what=2;
        handler.sendMessage(message2);
        try {
            fis.close();
        } catch (Exception e) {
        }
        
        return apkFile.getAbsolutePath();
    }
    
    public HttpClient getDefaultHttpClient(int connectionTimeout) {
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), connectionTimeout);
        HttpConnectionParams.setSoTimeout(client.getParams(), connectionTimeout);
        client.getParams().setParameter("Content-type", "application/json;charset=utf-8");
        return client;
    }
    
    /**Object->Integer*/
    public static Integer getInteger(Object obj){
        Integer res = 0;
        if(obj != null){
            try{
                res = Integer.valueOf(obj + "");
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return res;
    }

Custom_Dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt_downTitle"
        android:textSize="@dimen/textsize_middle"/>
    
    <ProgressBar 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/proBar_downBar"
        style="?android:attr/progressBarStyleHorizontal"
        />

</LinearLayout>

 

posted @ 2012-06-01 14:28  暗殇  阅读(336)  评论(0编辑  收藏  举报