2016-04-15 204 views
0

我正在開發一個應用程序,如果有任何新的應用程序正在安裝在設備中,我必須從該應用程序的包名獲取應用程序名稱,當應用程序正確安裝爲此,我正在做下面的代碼。但它始終顯示(未知)消息給我不是應用程序名稱。請幫助我。如何從Android的包名獲取應用程序名稱?

這裏是我的代碼: -

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) {} 
相關問題