關於DownloadManager的一些問題

我們都知道自動升級  可以調取安卓系統的downloadManager來完成下載。

我是遇到一個問題,在調遊標查詢的時候,查詢的遊標爲空,並且下面的download會參數非法異常。

後來經過研究,發現是因爲安卓手機的下載管理器有時會關閉,導致我根本查不到下載器,也就沒辦法下載了

其實我們可以自己寫一個的,也不費事,下面貼代碼。



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center_horizontal"
    android:background="#fff"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開始"
        android:gravity="center"
        android:textSize="15sp"
        />


</LinearLayout>


public class MainActivity extends Activity implements View.OnClickListener {


    private ImageView dong;
    private Intent intent;
    private Button download;
    private static final String URL_STRING = "http://www.shoufangbao.net/download.php?canal=400";
    private static int down = 0;
    File file;
    private Button downlaod;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            switch (msg.what) {
                case 1:
                    download.setText("點擊安裝");
                    down = 1;
                    break;
                case 2:
                    down = 2;
                    download.setText("打開");
                    break;
            }
        }


    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        downlaod = (Button) findViewById(R.id.start);
        downlaod.setOnClickListener(this);
        if (down != 0) {
            down = 0;
        }


    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:
                PackageManager manager = this.getPackageManager();
                Intent intent = manager.getLaunchIntentForPackage("com.kupangstudio.shoufangbao");
                // 下載apk
                if (down == 0) {
                    if (intent == null) {
                        downFile(URL_STRING);
                        download.setText("正在下載");
                    } else {
                        Toast.makeText(this, "親,您已經安裝該應用,可直接打開。", Toast.LENGTH_SHORT).show();
                        Message message = handler.obtainMessage();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                    // 安裝APK
                } else if (down == 1) {
                    installApk();
                    // 打開apk
                } else if (down == 2) {
                    openApk(this, URL_STRING);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 後臺在下面一個Apk 下載完成後返回下載好的文件
     *
     * @param httpUrl
     * @return
     */
    private File downFile(final String httpUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                file = getFile();
                if (!file.exists()) {
                    try {
                        URL url = new URL(httpUrl);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout(5000);
                        FileOutputStream fileOutputStream = null;
                        InputStream inputStream;
                        if (connection.getResponseCode() == 200) {
                            inputStream = connection.getInputStream();


                            if (inputStream != null) {
                                file = getFile();
                                fileOutputStream = new FileOutputStream(file);
                                byte[] buffer = new byte[1024];
                                int length = 0;


                                while ((length = inputStream.read(buffer)) != -1) {
                                    fileOutputStream.write(buffer, 0, length);
                                }
                                fileOutputStream.close();
                                fileOutputStream.flush();
                            }
                            inputStream.close();
                        }


                        System.out.println("已經下載完成");
                        // 往handler發送一條消息 更改button的text屬性
                        Message message = handler.obtainMessage();
                        message.what = 1;
                        handler.sendMessage(message);


                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }
        }).start();


        return file;
    }


    // 接收到安裝完成apk的廣播
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("接收到安裝完成apk的廣播");
            Message message = handler.obtainMessage();
            message.what = 2;
            handler.sendMessage(message);
        }
    };


    @Override
    public void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addDataScheme("package");
        // 註冊一個廣播
        this.registerReceiver(broadcastReceiver, intentFilter);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // 解除廣播
        this.unregisterReceiver(broadcastReceiver);
    }


    /**
     * 安裝APK
     */
    private void installApk() {
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }


    /**
     * 打開已經安裝好的apk
     */
    private void openApk(Context context, String url) {
        /*PackageManager manager = context.getPackageManager();
        // 這裏的是你下載好的文件路徑
        Toast.makeText(MainActivity.this,"manager",Toast.LENGTH_SHORT).show();
        PackageInfo info = manager.getPackageArchiveInfo(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "shoufangbao.apk", PackageManager.GET_ACTIVITIES);
        Toast.makeText(MainActivity.this,"info="+info,Toast.LENGTH_SHORT).show();
        if (info != null) {
            Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
            Toast.makeText(MainActivity.this,"intent",Toast.LENGTH_SHORT).show();
            startActivity(intent);
        }
*/
        PackageManager manager = context.getPackageManager();
        Intent intent = manager.getLaunchIntentForPackage("com.kupangstudio.shoufangbao");
        startActivity(intent);
    }


    /**
     * 根據傳過來url創建文件
     */
    private File getFile() {


        File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "shoufangbao.apk");


        return files;
    }


   /* *//**
     * 截取出url後面的apk的文件名
     *
     * @param url
     * @return
     *//*
    private String getFilePath(String url) {
        return url.substring(url.lastIndexOf("/"), url.length());
    }*/
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章