2013-01-08 147 views
7

我找的,我希望得到他device.I用戶打開或安裝應用的解決方案必須得到該應用程序被用戶從我的廣播接收器class.I打開已經實現了我的代碼如下:如何獲取用戶當前打開的應用程序?

public class AppReceiver extends BroadcastReceiver{ 

@Override 
public void onReceive(Context context, Intent intent) { 

    ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE); 
    List l = am.getRunningAppProcesses(); 
    Iterator i = l.iterator(); 
    PackageManager pm = context.getPackageManager(); 
    while(i.hasNext()) { 
     ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next()); 
     try { 

     CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA)); 
     Log.v(" App Name : ", c.toString()); 


     }catch(Exception e) { 
     } 
    } 


} 

我也加入了這個rec​​iever清單文件爲:

<receiver android:name="AppReciever"> 
     <intent-filter> 
      <category android:name="android.intent.category.DEFAULT" /> 
      <action android:name="android.intent.action.PACKAGE_ADDED"></action> 
      <action android:name="android.intent.action.PACKAGE_CHANGED"></action> 
      <action android:name="android.intent.action.PACKAGE_INSTALL"></action> 
      <action android:name="android.intent.action.PACKAGE_REPLACED"></action> 
      <action android:name="android.intent.action.PACKAGE_RESTARTED"></action> 
    <data android:scheme="package" /> 

    </intent-filter> 
    </receiver> 

從當我打開它已經存在的新的應用程序(安置)在上面的代碼AppReciver不執行在Log.v獲取應用程序名稱該設備。它只在其他應用程序運行一次的設備上工作。

請任何機構幫我從廣播接收器

+0

我得到的應用程序名稱唯一的新package_added但我如果package_restarted/package_install/package_replaced/package_restarted –

+0

我很抱歉,我不能讓你在問什麼讓,你能替我解釋一下你的問題嗎? 你想獲得所有安裝的應用程序嗎? –

回答

2

得到當前打開的應用程序添加到您服務registerReceiver()。不要忘記取消註冊接收者;

AppReceiver appReceiver = new AppReceiver(); 
    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.setPriority(900); 
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 
    intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); 
    intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL); //@deprecated This constant has never been used. 
    intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED); 
    intentFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED); 
    registerReceiver(appReceiver, intentFilter); 

對於註銷:unregisterReceiver(appReceiver);

+0

使用Integer.MAX_VALUE的優先級是否有任何傷害? – gonzobrains

+1

從SYSTEM_HIGH_PRIORITY值的IntentFilter類文檔:應用程序絕不應使用具有此優先級或更高優先級的篩選器。 – resource8218

相關問題