2014-09-17 5 views
0

Я хочу написать приложение, устанавливающее новое приложение. Файл .apk для этого нового приложения включен в ресурсы (R.raw.snake). Можете ли вы дать мне код для установки приложения snake.apk программно? Моя текущая проблема заключается в том, что я не могу получить доступ к файлу как java.io.File, но только как InputStream. Я нашел этот код:Установка файла apk из ресурсов

File file = new File(this.getFilesDir() + File.separator + "Snake.apk"); 
try { 
    InputStream inputStream = getResources().openRawResource(R.raw.snake); 
    FileOutputStream fileOutputStream = new FileOutputStream(file); 

    byte buf[]=new byte[1024]; 
    int len; 
    while((len=inputStream.read(buf))>0) { 
     fileOutputStream.write(buf,0,len); 
    } 

    fileOutputStream.close(); 
    inputStream.close(); 
} catch (IOException e1) {} 
Installer installer = new Installer(this, file); 
installer.install(); 

Но я получаю сообщение об ошибке на моем экране планшета:

Parse error 
There was a problem while parsing the package. 

Это мой класс Installer:

package de.rbg.continental.bluetoothclient2; 

import java.io.File; 
import java.util.List; 

import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.net.Uri; 
import android.util.Log; 

public class Installer { 

private static Context context = null; 
private static File file = null; 
public static final String PACKAGE_NAME = "de.rbg.home.snake"; 
private static Receiver receiver = null; 
private static final String TAG = "de.rbg.continental.nfcclient3.Installer"; 

public Installer(Context context, File file){ 
    Installer.context = context; 
    Installer.file = file; 
} 

public boolean install(){ 
    if (!isAppInstalled()){ 
     registerReceiver(); 
     installApk(); 
     return true; 
    } 
    return false; 
} 

private boolean installApk(){ 
    try { 
     Log.v(TAG, "installing file: " + file.getPath()); 
     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 
     context.startActivity(intent); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
    return true; 
} 

private boolean isAppInstalled(){ 
    List list = getListOfInstalledApps(); 
    for (int i = 0; i < list.size();i++){ 
     if (list.get(i).toString().contains(PACKAGE_NAME)) 
      return true; 
    } 
    return false; 
} 

private List getListOfInstalledApps(){ 
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    return context.getPackageManager().queryIntentActivities(mainIntent, 0); 
} 

private void registerReceiver(){ 
    receiver = new Receiver(); 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction(Intent.ACTION_PACKAGE_ADDED); 
    context.registerReceiver(receiver, filter); 
} 

public static void unregisterReceiver(){ 
    context.unregisterReceiver(receiver); 
} 

public static void onApkInstalled(){ 
    unregisterReceiver(); 
} 
} 

Предложения приветствуются.

+0

вы можете установить файл snake.apk из вашей файловой системы напрямую? –

+0

** ПОЧЕМУ ** Вы должны когда-нибудь делать что-то подобное? –

+0

Никто не может сказать вам, почему у вас есть эта ошибка синтаксического анализа, поскольку в вашем коде нет ничего, что анализирует. И вы не сказали, от кого вы получили эту ошибку. Мы должны угадать? – greenapps

ответ

1
Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() 
     + "<Path To Your APK>")), 
    "application/vnd.android.package-archive"); 
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent); 
+0

, это не то, что мне нужно. Я знаю, как установить apk-файл, но я не знаю, как установить файл apk, который хранится в файле ресурсов – Garrarufa

0

Теперь я узнал, что ошибка была вызвана отсутствующими разрешениями в файле манифеста:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
Смежные вопросы