Android 下载APK 安装APK 打开APK

来源:互联网 发布:足球比赛抽签软件 编辑:程序博客网 时间:2024/04/30 01:16

今天有了一个这样的需求 :下载一个apk文件,然后当你下载完成后,按钮的文字发生改变,变成点击安装,然后安装完成之后,变成打开。

这是下载apk的方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
     * 后台在下面一个Apk 下载完成后返回下载好的文件
     *
     * @param httpUrl
     * @return
     */
    privateFile downFile(finalString httpUrl) {
 
        newThread(newRunnable() {
 
            @Override
            publicvoidrun() {
                try{
                    URL url = newURL(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(httpUrl);
                            fileOutputStream = newFileOutputStream(file);
                            byte[] buffer = newbyte[1024];
                            intlength = 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();
                }
            }
        }).start();
        returnfile;
    }


这是安装APK的方法:

?
1
2
3
4
5
6
7
8
/**
     * 安装APK
     */
    privatevoidinstallApk() {
        Intent intent = newIntent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        startActivity(intent);
    }


这是打开APK的方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
     * 打开已经安装好的apk
     */
    privatevoidopenApk(Context context, String url) {
        PackageManager manager = context.getPackageManager();
        // 这里的是你下载好的文件路径
        PackageInfo info = manager.getPackageArchiveInfo(Environment.getExternalStorageDirectory().getAbsolutePath()
                + getFilePath(url), PackageManager.GET_ACTIVITIES);
        if(info != null) {
            Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
            startActivity(intent);
        }
    }
打开APK 这里弄了好久,之前不知道有个getLaunchIntentForPackage方法 这个方法只要你能得到这个apk的报名,然后将包名加到后面,startActivity 它就会自动自动你的APK的主界面了。相信得到一个APK的的信息这个大家都会了,这里就不说了。


下面是我的所有代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
 * 下载Apk 安装Apk 打开APK
 *
 * @author Administrator
 *
 */
publicclassMainActivity extendsActivity {
    privateButton button1;
    privatestaticfinal String URL_STRING = "http://gdown.baidu.com/data/wisegame/b7d7e4efd8199dea/tianyiyuedu_310.apk";
    privatestaticint down = 0;
    File file;
 
    privateHandler handler = newHandler() {
 
        @Override
        publicvoidhandleMessage(Message msg) {
            super.handleMessage(msg);
 
            switch(msg.what) {
            case1:
                button1.setText("点击安装");
                down = 1;
                break;
            case2:
                down = 2;
                button1.setText("打开");
                break;
            }
        }
 
    };
 
    @Override
    protectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(newOnClickListener() {
 
            @Override
            publicvoidonClick(View v) {
                // 下载apk
                if(down == 0) {
                    downFile(URL_STRING);
                    button1.setText("正在下载");
                    // 安装APK
                }elseif(down == 1) {
                    installApk();
                    // 打开apk
                }elseif(down == 2) {
                    openApk(MainActivity.this, URL_STRING);
                }
 
            }
        });
 
    }
 
    // 接收到安装完成apk的广播
    BroadcastReceiver broadcastReceiver = newBroadcastReceiver() {
 
        @Override
        publicvoidonReceive(Context context, Intent intent) {
 
            System.out.println("接收到安装完成apk的广播");
 
            Message message = handler.obtainMessage();
            message.what = 2;
            handler.sendMessage(message);
        }
    };
 
    /**
     * 后台在下面一个Apk 下载完成后返回下载好的文件
     *
     * @param httpUrl
     * @return
     */
    privateFile downFile(finalString httpUrl) {
 
        newThread(newRunnable() {
 
            @Override
            publicvoidrun() {
                try{
                    URL url = newURL(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(httpUrl);
                            fileOutputStream = newFileOutputStream(file);
                            byte[] buffer = newbyte[1024];
                            intlength = 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();
                }
            }
        }).start();
        returnfile;
    }
 
    /**
     * 安装APK
     */
    privatevoidinstallApk() {
        Intent intent = newIntent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        startActivity(intent);
    }
 
    @Override
    protectedvoidonStart() {
        super.onStart();
 
        IntentFilter intentFilter = newIntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addDataScheme("package");
 
        // 注册一个广播
        registerReceiver(broadcastReceiver, intentFilter);
    }
 
    @Override
    protectedvoidonDestroy() {
        super.onDestroy();
        // 解除广播
        unregisterReceiver(broadcastReceiver);
    }
 
    /**
     * 打开已经安装好的apk
     */
    privatevoidopenApk(Context context, String url) {
        PackageManager manager = context.getPackageManager();
        // 这里的是你下载好的文件路径
        PackageInfo info = manager.getPackageArchiveInfo(Environment.getExternalStorageDirectory().getAbsolutePath()
                + getFilePath(url), PackageManager.GET_ACTIVITIES);
        if(info != null) {
            Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
            startActivity(intent);
        }
    }
 
    /**
     * 根据传过来url创建文件
     *
     */
    privateFile getFile(String url) {
        File files = newFile(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url));
        returnfiles;
    }
 
    /**
     * 截取出url后面的apk的文件名
     *
     * @param url
     * @return
     */
    privateString getFilePath(String url) {
        returnurl.substring(url.lastIndexOf("/"), url.length());
    }
}


布局文件就只要一个按钮,就不贴出来了。还有一个东西,就是监听一个应用安装完成的广播,我这里是直接在代码中注册:

?
1
2
3
4
5
IntentFilter filter = newIntentFilter(); 
       
    filter.addAction("android.intent.action.PACKAGE_ADDED"); 
    filter.addAction("android.intent.action.PACKAGE_REMOVED"); 
    filter.addDataScheme("package");

监听安装apk和卸载apk的广播,其它的相信大家看代码也能看懂了,代码有点粗糙(菜鸟一枚),有哪里写的不好的地方,欢迎大家指正。

这个程序我没有考虑其他的情况,比如apk安装出错了,要怎么处理,等等。。

忘记说了,还需要在配置文件中添加访问网络和往sd卡写文件的权限:

?
1
2
<uses-permission android:name="android.permission.INTERNET">
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission></uses-permission>



转载地址:http://www.2cto.com/kf/201405/303571.html



  
0 0
原创粉丝点击