2013-01-16 8 views
5

インストールステータスに関する情報を取得するために、apkファイルをインストールしてブロードキャストレシーバを設定します。私はBroadcastReceiverクラスを準備したAndroid:BroadcastReceiver on applicationインストール/アンインストール

:主な活動で

public class newPackageReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("DEBUG"," test for application install/uninstall"); 
    } 

} 

、Iは、まずアプリケーションのインスタンス化ボタンがインストール、新しいレシーバオブジェクトを登録します。私OnclickListenerクラスで

public void onCreate(Bundle savedInstanceState) { 
... 
IntentFilter filter = new IntentFilter(); 
     filter.addAction(Intent.ACTION_PACKAGE_ADDED); 
     filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 
     filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED); 
     filter.addAction(Intent.ACTION_PACKAGE_INSTALL); 
     filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 
     filter.addAction(Intent.ACTION_PACKAGE_REPLACED); 
     filter.addAction(Intent.ACTION_PACKAGE_RESTARTED); 

     receiver = new newPackageReceiver(); 
     registerReceiver(receiver, filter); 
     ... 

dlButton.setText(R.string.dl_button); 
dlButton.setOnClickListener(new AppliDownloadOnClickListener(this)); 


@Override 
public void onDestroy(){ 
    unregisterReceiver(receiver); 
    super.onDestroy(); 
} 

、私は入れ:

@Override 
    public void onClick(View v) { 

    // actually, the below process is in an asyncTask 
    URL url; 
    Intent promptInstall; 

    try { 
     url = new URL(apkurl); 

     HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
     c.setRequestMethod("GET"); 
     c.setDoOutput(true); 
     c.connect(); 

     String PATH = Environment.getExternalStorageDirectory()+ "/download/"; 
     File file = new File(PATH); 
     file.mkdirs(); 
     File outputFile = new File(file, "app.apk"); 
     FileOutputStream fos = new FileOutputStream(outputFile); 

     InputStream is = c.getInputStream(); 

     byte[] buffer = new byte[1024]; 
     int len1 = 0; 
     while ((len1 = is.read(buffer)) != -1) { 
      fos.write(buffer, 0, len1); 
     } 

     fos.close(); 
     is.close(); 

     promptInstall = new Intent(Intent.ACTION_VIEW); 
     promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive"); 

     if (promptInstall != null) { 
      activity.startActivity(promptInstall); 
     } else { 
      ErrorDetails.displayToastMessage(activity,R.string.connection_error); 
     } 


    } catch (...) { 
     ... 
    } 

} 

上記のコード(私はそれを縮小している)ボタンがクリックされたときに、インストーラは、表示され、アプリケーションが完全にインストールされているが、受信機のクラスで(newPackageReceiver)が呼び出されることはありません。登録(registerReceiver)はonCreateメソッドで行われ、unregisterReceiverはonDestroyメソッドで呼び出されるため、有効になります。なぜなのかご存知ですか ?

ありがとうございます!

答えて

5

インテントフィルタにdata schemeを追加する必要があります。

filter.addDataScheme("package"); 

また、ACTION_PACKAGE_INSTALLは使用されていませんでした。

+0

完璧〜それは動作します! ACTION_PACKAGE_INSTALL〜 – johann

+0

について、データスキームと情報をありがとうございます。 – aotian16