2016-04-15 20 views
0

新しいアプリがデバイスにインストールされている場合、そのアプリが正しくインストールされたときにそのアプリのパッケージ名からアプリ名を取得する必要があるアプリを開発しています。それは常に(未知の)私にアプリ名ではないメッセージを表示します。私を助けてください。ここパッケージ名からアンドロイドのアプリ名を取得するには?

は私のコードです: -

public class Receiver extends BroadcastReceiver { 
    public Context context; 
    public String title; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Get application status(Install/ Uninstall) 
     @SuppressWarnings("UnusedAssignment") boolean applicationStatus = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 
     String toastMessage = null; 

     // Check if the application is install or uninstall and display the message accordingly 
     if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) { 
      // Application Install 
      toastMessage = "PACKAGE_INSTALL: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString()); 
     } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) { 

      // Application Uninstall 
      toastMessage = "PACKAGE_REMOVED: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString()); 
     } else if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) { 
      // Application Replaced 
      toastMessage = "PACKAGE_REPLACED: " + intent.getData().toString() + getApplicationName(context, intent.getData().toString()); 
     } 

     //Display Toast Message 
     if (toastMessage != null) { 
      Toast.makeText(context, toastMessage, Toast.LENGTH_LONG).show(); 
     } 
     System.out.println("App Name:" + title); 
    } 

    /** 
    * This method get application name name from application package name 
    */ 
    private String getApplicationName(Context context, String data) { 

     final PackageManager pckManager = context.getPackageManager(); 
     ApplicationInfo applicationInformation; 
     try { 
      applicationInformation = pckManager.getApplicationInfo(data, 0); 
     } catch (PackageManager.NameNotFoundException e) { 
      applicationInformation = null; 
     } 

     title = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)"); 
     return title; 

    } 
} 

答えて

0

PackageManager

import android.content.pm.ApplicationInfo; 
import android.content.pm.PackageManager; 
import android.content.pm.PackageManager.NameNotFoundException; 

PackageManager pkManager = getPackageManager(); 
     ApplicationInfo appInfo; 
     String packageName=getApplicationContext().getApplicationInfo().packageName; 
     try { 
      appInfo = pkManager.getApplicationInfo(packageName, 0); 
      final String appname = (String)((appInfo != null) ? pkManager.getApplicationLabel(appInfo) : "???"); 
        Log.e("appname", appname); 
     } catch (final NameNotFoundException e) {} 
を使用する必要があります
関連する問題