我试图在android中获取所有应用程序的列表并计算发送和接收的字节数,但下面的代码给出了不是应用程序名称的pickage名称:
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningProcesses = manager.getRunningAppProcesses();
if (runningProcesses != null && runningProcesses.size() > 0) {
// Set data to the list adapter
setListAdapter(new ListAdapter(this, runningProcesses));
}
else {
// In case there are no processes running
Toast.makeText(getApplicationContext(), "No application is running", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
long send = 0;
long recived = 0;
long wr,ws,mr,ms =0;
// Get UID of the selected process/ application
int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;
// Get traffic data
recived = TrafficStats.getUidRxBytes(uid);
send = TrafficStats.getUidTxBytes(uid);
// Get Mobile data:
mr = TrafficStats.getTotalRxBytes();
ms = TrafficStats.getMobileTxBytes();
//GetWifiDataA:
wr = (TrafficStats.getTotalRxBytes())- (TrafficStats.getMobileRxBytes());
ws = (TrafficStats.getTotalTxBytes())- (TrafficStats.getMobileTxBytes());
// Display data
Toast.makeText(getApplicationContext(), " \nUID " + uid + " details.. \nWifi Send: " +ws /1000+" \n Wifi Received: " +wr/1000+"kB"+ "\n Mobile Send: "+ms/1000+" kB"+"\n Mobile Received: "+mr/1000+"kB",Toast.LENGTH_LONG).show();
}
解决
包管理器的代码解决了这个问题:
packageManager = getPackageManager();
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_META_DATA);
apkList = (ListView) findViewById(R.id.applist);
apkList.setAdapter(new ApkAdapter(this, packageList, packageManager));
on next activity:
int app_uid = packageInfo.applicationInfo.uid;
long send = 0;
long recived = 0;
// Get traffic data
recived = TrafficStats.getUidRxBytes(app_uid);
send = TrafficStats.getUidTxBytes(app_uid);
// APP name
appLabel.setText(getPackageManager().getApplicationLabel(
packageInfo.applicationInfo));
// package name
packageName.setText(packageInfo.packageName);
// version name
version.setText(packageInfo.versionName);
// received
andVersion.setText(Long
.toString(recived));
// send
path.setText(Long.toString(send));
答案 0 :(得分:3)
像这样编写你的代码......它返回所有已安装的应用程序名称的arraylist ..
public ArrayList<String> getAppnames() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> activities = getPackageManager().queryIntentActivities( mainIntent, 0);
ArrayList<String>appList=new ArrayList<String>();
for (ResolveInfo resolveInfo : activities) {
appList.add(resolveInfo.loadLabel(getPackageManager()).toString());
}
return appList;
}