2015-12-21 147 views
-1

我正在使用自定義鍵盤,鍵盤打開時需要當前的包名稱。這個鍵盤將會以不同的應用程序打開,所以我需要那個當前打開的應用程序包名稱。我正在使用下面的代碼,但它不能正常工作。Android獲取當前打開的應用程序的包名稱

ActivityManager mActivityManager = (ActivityManager)PhotoActivity.this.getSystemService(Context.ACTIVITY_SERVICE); 
      if(Build.VERSION.SDK_INT > 20){ 
       String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName; 
       Log.e("Checking package:  ","Checking current application package"+mPackageName); 
      } 
      else{ 
       String mPackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName(); 
      } 
+1

這是一個約一千個問題重複。僅供參考,您使用的破解在Android 5.1.1和6.0中被破解。官方認可的替代品是Usage Stats API,但它不適用於所有設備。 –

回答

1

在android系統

 ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); 
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 

// display the current class name 
     Toast.makeText(getApplicationContext(), taskInfo.get(0).topActivity.getClassName(), Toast.LENGTH_LONG).show(); 
     ComponentName componentInfo = taskInfo.get(0).topActivity; 

// current class package name 
      String packageName = componentInfo.getPackageName(); 
獲取當前包名

添加到您的項目清單的權限

<uses-permission android:name="android.permission.GET_TASKS"/> 
0
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 

Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getPackageName()); 
+0

這個破解在Android 5.0中被破解。 –

+0

嗨,它返回null –

0

使用下面的代碼: -

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); 
List l = am.getRecentTasks(1, ActivityManager.RECENT_WITH_EXCLUDED); 
Iterator i = l.iterator(); 
PackageManager pm = this.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.w("LABEL", c.toString()); 
    } catch (Exception e) { 
     // Name Not FOund Exception 
    } 
} 

而且不要忘記使用許可

<uses-permission android:name="android.permission.GET_TASKS"/> 
+0

嗨Ravindra Kushwaha,感謝您的答覆。它不能正常工作,因爲它獲得自定義鍵盤的相​​同包名稱而不是當前正在運行的打開的應用程序。我正在使用Android 5.0 –

+0

@SakibSyed ...好吧...讓我試試... –

相關問題