Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster or cleaner way to find out if a package is installed on Android

Tags:

java

android

I know that I can either catch the NameNotFoundException from a call to PackageManager.getPackageInfo or loop through the PackageInfo list returned by PackageManager.getInstalledPackages to know whether a particular package is installed, but both of these seem either long winded or ugly. On my personal phone, I have more than 300 packages installed, so I'd hate to have to do that operation every time I need to check. And catching an exception as a means of performing application logic just makes me feel wrong all over. Am I missing the isPackageInstalled method somewhere, or do I just need to implement it myself using one of the above mentioned techniques? And if the latter, which would be considered the faster and less resource intensive option?

like image 461
Rich Avatar asked Oct 06 '22 20:10

Rich


2 Answers

Since PackageManager.getInstalledPackages() returns a List, you don't need to loop through it manually. You can use List.contains() or List.containsAll() to accomplish the task in one line of code. Of course, this doesn't change the efficiency since both methods likely contain a loop themselves.

like image 153
Code-Apprentice Avatar answered Oct 11 '22 01:10

Code-Apprentice


If using the API really bugs you then you might look into a hack involving the following

Bash shell expression that gets the PM list Java Runtime expression Java Pipes and buffers and streams Java NIO Java grep

So the bash expression would be :

pm list packages -f | sed 's/^package.//' | awk -F"=" ' { print $2" "$1 } ' | sort

and of list of references for handling stdout from the 'pm list' in a way that might wind up being faster...

PipedBuffers

NIO/grep

Runtime/streams

like image 44
Robert Rowntree Avatar answered Oct 11 '22 03:10

Robert Rowntree