`

upgrade

阅读更多
package com.example.version_upgrade;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{

    private int versionCode_self;
    private static final int UPGRADE = 0;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PackageInfo packageInfo;
        try
        {
            //得到当前应用的版本
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            versionCode_self=packageInfo.versionCode;
            //查看市场的最新版本  ,apk都有 说明书,先要读说明书的内容 ,版本号,与自己 的版本号比较
            String  url="http://169.254.104.44:8080/version.txt";
            new DownSpecifications().execute(url);
           
        }
        catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
  //下载apk的说明 书,做activity的内部类,是可以掉activity的方法   showDialog(0, null);
    class DownSpecifications  extends  AsyncTask<String, Void, String>
    {

       
      
        @Override
        protected String doInBackground(String... params)
        {
            InputStream is =null;
            try
            {
                URL url = new URL(params[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                if(con.getResponseCode()!=HttpURLConnection.HTTP_OK)
                {
                    Log.e("HttpURLConnection", "连接异常");
                    return null;
                }
                is = con.getInputStream();
                byte[] buffer=new byte[1024];
                int len=0;
                StringBuilder sb = new StringBuilder();
                while(-1!=(len=is.read(buffer)))
                {
                    sb.append(new String(buffer, 0, len));
                }
                return sb.toString();
            }
            catch (MalformedURLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally
            {
                if(is!=null)
                    try
                    {
                        is.close();
                    }
                    catch (IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result)
        {
               try
            {
                JSONObject jsonObject = new JSONObject(result);
                int versionCode = jsonObject.getInt("versionCode");
                url = jsonObject.getString("url");
                //内部类的好处,又可以拿activity的versionCode来比较,外部类就要通过构造函数传了
                if(versionCode_self<versionCode)
                    showDialog(UPGRADE, null);
            }
            catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }
       





    }
    @Override
    protected Dialog onCreateDialog(int id, Bundle args)
    {
        switch (id)
        {
        case UPGRADE:
            Dialog dialog = new Dialog(this);
            dialog.setTitle("有最新版本,是否要升级");
             View view = getLayoutInflater().inflate(R.layout.upgrade, null);
             Button button = (Button) view.findViewById(R.id.button1);
             button.setOnClickListener(new OnClickListener()
            {  
               
                @Override
                public void onClick(View v)
                {
                    dismissDialog(UPGRADE);
                    //启动一个服务来下载,notification里显示下载进度,如果在activity里显示进度就影响用户操作体验不好
                    //在此要传个要下载apk的地址  ,在读apk说明书的时候得到
                    Intent intent=new Intent(MainActivity.this, MyService.class);
                    intent.putExtra("url", url);
                    startService(intent);
                }
            });
            dialog.setContentView(view);
           
            return dialog;
        default:
            break;
        }
        return super.onCreateDialog(id, args);
    }


}
///////////////////////////////////////////////////////////////////
package com.example.version_upgrade;

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.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyService extends Service
{
    private Notification notification;
    private ProgressBar progress;
    private RemoteViews remoteViews;
    private String apkName;
    private NotificationManager manager;

    public MyService()
    {
    }
    @Override
    public void onCreate()
    {
        //请求网络前,下make  notification
      
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notification=new Notification(R.drawable.ic_launcher, "通知", System.currentTimeMillis());
        //flags 设为FLAG_NO_CLEAR 就不会消失
        notification.flags=Notification.FLAG_NO_CLEAR;
        remoteViews=new RemoteViews(getPackageName(), R.layout.notification);
        //false是说明进度条不是无限进度 ,进度就100
        remoteViews.setProgressBar(R.id.progressBar1, 100, 0, false);
        notification.contentView=remoteViews;
        Intent intent1=new Intent(this, MainActivity.class);
        notification.contentIntent=PendingIntent.getActivity(this, 0, intent1, 0);
        manager.notify(R.drawable.ic_launcher, notification);
       
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        String url = intent.getStringExtra("url");
        getAPKname(url);
        new DowmAPK().execute(url);
        return super.onStartCommand(intent, flags, startId);
    }

    private void getAPKname(String url)
    {
       int lastIndexOf = url.lastIndexOf('/');
       apkName = url.substring(lastIndexOf+1);
    }
    @Override
    public IBinder onBind(Intent intent)
    {
       return  null;
    }
   class DowmAPK  extends  AsyncTask<String, Integer, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            InputStream is =null;
            FileOutputStream fos=null;
            try
            {
                URL url = new URL(params[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                if(con.getResponseCode()!=HttpURLConnection.HTTP_OK)
                {
                    Log.e("HttpURLConnection", "连接异常");
                    return null;
                }
                int contentLength = con.getContentLength();
                is = con.getInputStream();
                fos = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+apkName);
               
                byte[] buffer=new byte[1024];
                int len=0;
                int len2=0;
                StringBuilder sb = new StringBuilder();
                while(-1!=(len=is.read(buffer)))
                {
                    len2+=len;
                    publishProgress(len2,contentLength);
                    fos.write(buffer, 0, len);
                   
                }
                return "down ok!!!";
            }
            catch (MalformedURLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally
            {
                if(is!=null)
                    try
                    {
                        is.close();
                    }
                    catch (IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                 if(fos!=null)
                    try
                    {
                        fos.close();
                    }
                    catch (IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(Integer... values)
        {
            Log.e("onProgressUpdate", "onProgressUpdate");
            //values[1]  总字节  values[0]已经读了的字节
            remoteViews.setProgressBar(R.id.progressBar1, values[1], values[0], false);
           
            Log.e("onProgressUpdate22", "onProgressUpdate22");
           // Post a notification to be shown in the status bar.
            //If a notification with the same id has already been posted by your application
            //and has not yet been canceled,
            //it will be replaced by the updated information.

            //更新notification的内容,一定要通知,就是调下面的方法,不然进度条不会更新的
            manager.notify(R.drawable.ic_launcher, notification);
        }
        @Override
        protected void onPostExecute(String result)
        {
            if(result!=null)
            {
                notification.flags=Notification.FLAG_AUTO_CANCEL;
                manager.notify(R.drawable.ic_launcher, notification);
            Toast.makeText(getApplication(), "下载完毕", Toast.LENGTH_LONG).show();
       
        
              String fileName = Environment.getExternalStorageDirectory() +"/"+apkName;
              //启动系统的activity
              Intent intent = new  Intent(Intent.ACTION_VIEW);
              intent.setDataAndType(Uri.fromFile(new  File(fileName)),"application/vnd.android.package-archive");
              //不是在activity里   要加这句话
              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(intent);           
            }         
           
       
       
        }
       
       
       
       
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics