Android安装assets内APK

1.创建工程后AndroidManifest.xml里面需要添加的两个权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

2.先创建assets文件夹 把安装包复制进里面 重命名为xiaoxin.mp3 获取assets资源目录下的xiaoxin.mp3,实际上是apk,为了避免被编译压缩,修改后缀名。

3.下面是java里面添加的点击事件代码

AssetManager assets = getAssets();
					try
					{

						InputStream stream = assets.open("xiaoxin.mp3");
						if(stream==null)
						{

						}

						String folder = "/mnt/sdcard/sm/";
						File f=new File(folder);
						if(!f.exists())
						{
							f.mkdir();
						}
						String apkPath = "/mnt/sdcard/sm/xiaoxin.apk";
						File file = new File(apkPath);
						//创建apk文件
						file.createNewFile();
						//将资源中的文件重写到sdcard中
						//
						writeStreamToFile(stream, file);
						//安装apk
						//			
						installApk(apkPath);
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}		
				}

				private void writeStreamToFile(InputStream stream, File file)
				{
					try
					{
						//
						OutputStream output = null;
						try
						{
							output = new FileOutputStream(file);
						}
						catch (FileNotFoundException e1)
						{
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						try
						{
							try
							{
								final byte[] buffer = new byte[1024];
								int read;

								while ((read = stream.read(buffer)) != -1)
									output.write(buffer, 0, read);

								output.flush();
							}
							finally
							{
								output.close();
							}
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
					}
					finally
					{
						try
						{
							stream.close();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				private void installApk(String apkPath)
				{
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setDataAndType(Uri.fromFile(new File(apkPath)),
										  "application/vnd.android.package-archive");
					startActivity(intent);
 版权声明:本文为AIDE教程网原创文章,转载请附上原文出处链接和本声明
本文链接: https://www.aidemx.cn/306.html

梦雪

专注于AIDE教程分享

    留下你的评论

    *评论支持代码高亮<pre class="prettyprint linenums">代码</pre>

    相关推荐