您的位置:首页 > 其它

关于DownloadManager的一些问题

2015-07-16 10:28 323 查看
我们都知道自动升级  可以调取安卓系统的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());

    }*/

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息