您的位置:首页 > 移动开发 > Android开发

Android:从assets资源目录下安装apk

2012-11-05 22:38 549 查看
为了实现将第三方apk内置在assets资源目录下,再进行安装的目的。

首先将需要安装的apk复制到assets目录下,后缀名改为.mp3或其他免压缩的格式。

测试代码如下:

public class MainActivity extends Activity
{
private static final String TAG = "ExtractIconFromApk";

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

AssetManager assets = getAssets();
try
{
//获取assets资源目录下的himarket.mp3,实际上是himarket.apk,为了避免被编译压缩,修改后缀名。
InputStream stream = assets.open("himarket.mp3");
if(stream==null)
{
Log.v(TAG,"no file");
return;
}

String folder = "/mnt/sdcard/sm/";
File f=new File(folder);
if(!f.exists())
{
f.mkdir();
}
String apkPath = "/mnt/sdcard/sm/test.apk";
File file = new File(apkPath);
//创建apk文件
file.createNewFile();
//将资源中的文件重写到sdcard中
//<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
writeStreamToFile(stream, file);
//安装apk
//<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
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)
{
Log.v(TAG,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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: