原文鏈接:http://blog.csdn.net/annkie/article/details/8150807
爲了實現將第三方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);
- }