Android Lock Apps - android

I'm new here and I've searched for questions to help me but I have no clear answers.
I need to make an application to block other applications on the phone.
I've seen several on the market but I want to make one.
is there any way of knowing when a user tries to open an application and bring forward an activity? (to put the password).
I tried with FileObserver, but only works with files and directories (obviously).
Could I make a listener that captures the Intent of the other applications before starting?
I apologize for my english and I appreciate your help!

No you cannot know when another application is launched without some kind of hack.
This is because application launches are not broadcasted.
What you can do is creating a service running on fixed intervals , say 1000 milliseconds, that checks what non system application is on front. Kill that app and from the service pop a password input box. If that password is correct relaunch that application
Here is some code sample
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
List<RunningAppProcessInfo> appProcesses= activityManager.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
try {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (!lastFrontAppPkg.equals((String) appProcess.pkgList[0])) {
apkInfo = ApkInfo.getInfoFromPackageName(appProcess.pkgList[0], mContext);
if (apkInfo == null || (apkInfo.getP().applicationInfo.flags && ApplicationInfo.FLAG_SYSTEM) == 1) {
// System app continue;
} else if (((apkInfo.getP().versionName == null)) || (apkInfo.getP().requestedPermissions == null)) {
//Application that comes preloaded with the device
continue;
} else {
lastFrontAppPkg = (String) appProcess.pkgList[0];
}
//kill the app
//Here do the pupop with password to launch the lastFrontAppPkg if the pass is correct
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}, 0, 1000);
And here is the ApkInfo.getInfoFromPackageName()
/**
* Get the ApkInfo class of the packageName requested
*
* #param pkgName
* packageName
* #return ApkInfo class of the apk requested or null if package name
* doesn't exist
* #see ApkInfo
*/
public static ApkInfo getInfoFromPackageName(String pkgName,
Context mContext) {
ApkInfo newInfo = new ApkInfo();
try {
PackageInfo p = mContext.getPackageManager().getPackageInfo(
pkgName, PackageManager.GET_PERMISSIONS);
newInfo.appname = p.applicationInfo.loadLabel(
mContext.getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(mContext
.getPackageManager());
newInfo.setP(p);
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
return newInfo;
}

there is a way to do so . you can know when a application is launched.
you can use packagemanager class to get all the information about any installed and inbuld application . and use the below code to know whwn that application is launched
#Override
public void run() { Log.i("test","detector run");
try {
Process process;
process = Runtime.getRuntime().exec(ClearLogCatCommand);
process = Runtime.getRuntime().exec(LogCatCommand);
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
// Check if it matches the pattern
while(((line=br.readLine()) != null) && !this.isInterrupted()){
Log.d("Detector", "RUN"+line);
// Ignore launchers
if (line.contains("cat=[" + Intent.CATEGORY_HOME + "]")) continue;
Matcher m = ActivityNamePattern.matcher(line);
if (!m.find()) continue;
if (m.groupCount()<2){
// Log.d("Detector", "Unknown problem while matching logcat output. Might be SDK version?");
continue;
}
if (mListener!=null) mListener.onActivityStarting(m.group(1), m.group(2));
Log.i("Detector", "Found activity launching: " + m.group(1) + " / " + m.group(2));
}
} catch (IOException e) {
e.printStackTrace();
}
}

You can now use an AccessibilityService that allows you to find out which Activity is at the top.
In the AccessibilityService class:
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity) {
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
}
You will have to turn the Accessibility on in your phone's settings, which can be done by going to Settings > Accessibility > Services > Your App. There are also a couple of permissions you'll have to add in your Manifest. A lot of the information can be found in the Android Developers site: http://developer.android.com/reference/android/accessibilityservice/AccessibilityService.html
Hope this helps!

Related

PJSUA2 Android - Incoming calls drop after 32 seconds

I'm building a PJSUA2 (PJSIP 2.8) Android app and I have some issues: i.e. only on incoming call, call state remains in "PJSIP_INV_STATE_CONNECTING" and after 32 seconds the call drops.
I'm looking for the cause of the issue since several days, I googled a lot and all what I found is: in most situations this issue is related to NAT management or network issues related to NAT. In a few words: in most cases the called party does not receive the ACK after answering the call.
Finally I was able to log all SIP messages between my app and the SIP server and found that my app receives the ACK from the server, so I suppose it's not a network related issue.
I compiled PJSIP 2.8 with OpenSSL and SRTP support, but without video support (I don't need it at least at the moment). If it makes any difference, the app has a target version 28 and minimum SDK version 19.
I tried several apps on the market and they work fine enough with and without SRTP and with all signaling transports (UDP, TCP, TLS), WebRTC works fine too (tested with SipML5), so I would exclude a server misconfiguration. My app does the same (except SRTP with which I have some issues at the moment).
I tried with a SIP provider too (MessageNet) using UDP and the behaviour is always the same. I tried to use compact SIP messages and it behaves the same, with and without uri parameters, with and without STUN and or ICE and nothing changes. Mobile network and WiFi networks give the same results.
I tried to debug inside PJSIP library too, but without any success, then I tried to follow the code, to understand what I was doing wrong, but it doesn't seem to me there is something evidently wrong.
The following is the code (last version) which initializes PJSIP:
public class SipService extends Service {
private Looper serviceLooper;
private ServiceHandler serviceHandler;
private final Messenger mMessenger = new Messenger(new IncomingHandler());
private LocalBroadcastManager localBroadcast;
private LifecycleBroadcastReceiver lifecycleBroadcastReceiver;
private boolean lastCheckConnected;
private Endpoint endpoint;
private LogWriter logWriter;
private EpConfig epConfig;
private final List<ManagedSipAccount> accounts = new ArrayList<>();
private final Map<String, Messenger> eventRegistrations = new HashMap<>();
#TargetApi(Build.VERSION_CODES.N)
#Override
public void onCreate() {
super.onCreate();
String userAgent = "MyApp";
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String appLabel = (pInfo.applicationInfo.labelRes == 0 ? pInfo.applicationInfo.nonLocalizedLabel.toString() : getString(pInfo.applicationInfo.labelRes));
userAgent = appLabel + "/" + pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
Log.e("SipService", "Unable to get app version", e);
}
try {
endpoint = new MyAppEndpoint();
endpoint.libCreate();
epConfig = new EpConfig();
// Logging
logWriter = new PJSIPToAndroidLogWriter();
epConfig.getLogConfig().setWriter(logWriter);
epConfig.getLogConfig().setLevel(5);
// UA
epConfig.getUaConfig().setMaxCalls(4);
epConfig.getUaConfig().setUserAgent(userAgent);
// STUN
StringVector stunServer = new StringVector();
stunServer.add("stun.pjsip.org");
epConfig.getUaConfig().setStunServer(stunServer);
// General Media
epConfig.getMedConfig().setSndClockRate(16000);
endpoint.libInit(epConfig);
// UDP transport
TransportConfig udpCfg = new TransportConfig();
udpCfg.setQosType(pj_qos_type.PJ_QOS_TYPE_VOICE);
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, udpCfg);
// TCP transport
TransportConfig tcpCfg = new TransportConfig();
//tcpCfg.setPort(5060);
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TCP, tcpCfg);
// TLS transport
TransportConfig tlsCfg = new TransportConfig();
endpoint.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS, tlsCfg);
endpoint.libStart();
} catch (Exception e) {
throw new RuntimeException("Unable to initialize and start PJSIP", e);
}
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
lastCheckConnected = activeNetwork != null && activeNetwork.isConnected();
updateForegroundNotification();
startForeground(MyAppConstants.N_FOREGROUND_NOTIFICATION_ID, buildForegroundNotification());
localBroadcast = LocalBroadcastManager.getInstance(this);
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Register LifeCycleBroadcastReceiver to receive network change notification
// It seems it's mandatory to do it programmatically since Android N (24)
lifecycleBroadcastReceiver = new LifecycleBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(lifecycleBroadcastReceiver, intentFilter);
}
// Initialization
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs != null) {
try {
CodecInfoVector codecs = endpoint.codecEnum();
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < codecs.size(); i++) {
CodecInfo codec = codecs.get(i);
int priority = prefs.getInt("codecs.audio{" + codec.getCodecId() + "}", 0);
try {
endpoint.codecSetPriority(codec.getCodecId(), (short) priority);
codec.setPriority((short) priority);
} catch (Exception e) {
Log.e("SipService", "Unexpected error setting codec priority for codec " + codec.getCodecId(), e);
}
}
} catch (Exception e) {
Log.e("SipService", "Unexpected error loading codecs priorities", e);
}
}
}
#Override
public void onDestroy() {
for (Account acc : accounts) {
acc.delete();
}
accounts.clear();
try {
endpoint.libDestroy();
} catch (Exception e) {
e.printStackTrace();
}
endpoint.delete();
endpoint = null;
epConfig = null;
if (lifecycleBroadcastReceiver != null) {
unregisterReceiver(lifecycleBroadcastReceiver);
}
super.onDestroy();
}
.......
}
And the following is my Account class with creation and registration code:
public class ManagedSipAccount extends Account {
public final String TAG;
private final VoipAccount account;
private final PhoneAccountHandle handle;
private final SipService service;
private final AccountStatus status;
private final Map<Integer, VoipCall> calls = new HashMap<>();
private final Map<String, VoipBuddy> buddies = new HashMap<>();
private AccountConfig acfg;
private List<SrtpCrypto> srtpCryptos = new ArrayList<>();
private AuthCredInfo authCredInfo;
public ManagedSipAccount(SipService service, VoipAccount account, PhoneAccountHandle handle) {
super();
TAG = "ManagedSipAccount/" + account.getId();
this.service = service;
this.account = account;
this.handle = handle;
this.status = new AccountStatus(account.getUserName() + "#" + account.getHost());
acfg = new AccountConfig();
}
public void register(Map<String, String> contactParameters) throws Exception {
StringBuilder contactBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : contactParameters.entrySet()) {
contactBuilder.append(';');
contactBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
contactBuilder.append("=\"");
contactBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
contactBuilder.append("\"");
}
StringBuilder logBuilder = new StringBuilder();
logBuilder.append("Registering: ");
logBuilder.append(account.getProtocol().name());
/*logBuilder.append('(');
logBuilder.append(service.getTransport(account.getProtocol()));
logBuilder.append(')');*/
if (account.isEncryptionSRTP()) {
logBuilder.append(" SRTP");
}
if (account.isIce()) {
logBuilder.append(" ICE");
}
Log.d(TAG, logBuilder.toString());
String idUri = "sip:" + account.getUserName();
if (!"*".equals(account.getRealm())) {
idUri += "#" + account.getRealm();
}
else {
idUri += "#127.0.0.1" /*+ account.getHost()*/;
}
acfg.setIdUri(idUri);
acfg.getRegConfig().setRegistrarUri("sip:" + account.getHost() + ":" + account.getPort() + ";transport=" + account.getProtocol().name().toLowerCase());
acfg.getRegConfig().setRetryIntervalSec(account.getRetryInterval());
acfg.getRegConfig().setRegisterOnAdd(false);
acfg.getSipConfig().setContactUriParams(contactBuilder.toString());
// NAT management
acfg.getNatConfig().setSipStunUse(pjsua_stun_use.PJSUA_STUN_USE_DEFAULT);
if (account.isIce()) {
acfg.getNatConfig().setIceEnabled(true);
acfg.getNatConfig().setIceAlwaysUpdate(true);
acfg.getNatConfig().setIceAggressiveNomination(true);
}
else {
acfg.getNatConfig().setSdpNatRewriteUse(1);
}
acfg.getMediaConfig().getTransportConfig().setQosType(pj_qos_type.PJ_QOS_TYPE_VOICE);
if (account.isEncryptionSRTP()) {
acfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_MANDATORY);
acfg.getMediaConfig().setSrtpSecureSignaling(0);
//acfg.getMediaConfig().getSrtpOpt().setKeyings(new IntVector(2));
acfg.getMediaConfig().getSrtpOpt().getKeyings().clear();
acfg.getMediaConfig().getSrtpOpt().getKeyings().add(pjmedia_srtp_keying_method.PJMEDIA_SRTP_KEYING_SDES.swigValue());
acfg.getMediaConfig().getSrtpOpt().getKeyings().add(pjmedia_srtp_keying_method.PJMEDIA_SRTP_KEYING_DTLS_SRTP.swigValue());
acfg.getMediaConfig().getSrtpOpt().getCryptos().clear();
StringVector cryptos = Endpoint.instance().srtpCryptoEnum();
for (int i = 0; i < cryptos.size(); i++) {
SrtpCrypto crypto = new SrtpCrypto();
crypto.setName(cryptos.get(i));
crypto.setFlags(0);
srtpCryptos.add(crypto);
acfg.getMediaConfig().getSrtpOpt().getCryptos().add(crypto);
}
}
else {
acfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_DISABLED);
acfg.getMediaConfig().setSrtpSecureSignaling(0);
}
authCredInfo = new AuthCredInfo("digest",
account.getRealm(),
account.getAuthenticationId() != null && account.getAuthenticationId().trim().length() > 0 ? account.getAuthenticationId() : account.getUserName(),
0,
account.getPassword());
acfg.getSipConfig().getAuthCreds().add( authCredInfo );
acfg.getIpChangeConfig().setHangupCalls(false);
acfg.getIpChangeConfig().setShutdownTp(true);
create(acfg);
ConnectivityManager cm = (ConnectivityManager)service.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnected();
if (isConnected) {
setRegistration(true);
}
}
#Override
public void onRegStarted(OnRegStartedParam prm) {
super.onRegStarted(prm);
Log.d(TAG, "Status: Registering...");
status.setStatus(AccountStatus.Status.REGISTERING);
service.updateStatus(this);
}
#Override
public void onRegState(OnRegStateParam prm) {
super.onRegState(prm);
try {
Log.d(TAG, "Registration state: " + prm.getCode().swigValue() + " " + prm.getReason());
AccountInfo ai = getInfo();
status.setStatus(ai.getRegIsActive() ? AccountStatus.Status.REGISTERED : AccountStatus.Status.UNREGISTERED);
Log.d(TAG, "Status: " + status.getStatus().name() + " " + super.getInfo().getUri());
service.updateStatus(this);
} catch (Exception e) {
e.printStackTrace();
}
}
.....
}
Finally, how I answer the code at the moment in a class which extends the PJSIP's Call class:
#Override
public void answerCall() {
Log.d(TAG, "Answering call...");
CallOpParam prm = new CallOpParam(true);
prm.setStatusCode(pjsip_status_code.PJSIP_SC_OK);
prm.getOpt().setAudioCount(1);
prm.getOpt().setVideoCount(0);
try {
this.answer(prm);
} catch (Exception e) {
e.printStackTrace();
}
}
I also tried with new CallOpParam(); with just the status code and nothing else, but nothing changes.
One note: I created the IdUri as sip:username#127.0.0.1 because without the host the resulting contact was and I thought that the missing user part may be the cause of the issue or part of it.
The following is the trace of the app <-> my Asterisk server communication during call (linked because of content length exceed).
https://gist.github.com/ivano85/a212ddc9a808f3cd991234725c2bdb45
The ServerIp is an internet public IP, while the MyIp[5.XXX.XXX.XXX] is my phone's public IP.
As you can see from the log, my app sends a 100 Trying, then a 180 Ringing when the phone rings, then the user answers and the app sends a 200 OK. The server replies with a ACK message (I would say it's not a NAT issue, because PJSIP receives the ACK). I see the same from Asterisk.
After this I would expect the call goes from PJSIP_INV_STATE_CONNECTING to PJSIP_INV_STATE_CONFIRMED, but it does not happen, so PJSIP continues to send a 200 OK and receive the ACK every about 2 seconds, until the call times out after 32 seconds and PJSIP disconnects the call (sending a BYE).
I'm starting to think that PJSIP just ignores ACK messages and just has a wrong behaviour. Please help me to understand what is happening here. I would appreciate it so much!
Obviously let me know if you think that more details are needed.

PackageManager getChangedPackages always return NULL

In my app I need to monitorize recently added or updated packages, but since Oreo this is a hard task.
To do it I have a service that runs every X time to detect the new installed/updated apps.
The main core of this service is to call the getChangedPackages function from the PackageManager, but this function always returns null, even if I install or update any app from or not from the Play Store in the interval between two consequtive calls to getChangedPackages.
https://developer.android.com/reference/android/content/pm/PackageManager.html#getChangedPackages(int)
I need to request any permission to call this function? Is the getChangedPackages buggy?
private void _doProcess()
{
try
{
PackageManager package_manager = getPackageManager();
int sequence_number = ApplicationPreferences.getInteger(this, GET_CHANGED_PACKAGES_SEQUENCE_NUMBER_KEY, 0);
ChangedPackages changed_packages = package_manager.getChangedPackages(sequence_number);
LogUtilities.show(this, String.format("Retrieve recently apps installs/updates using sequence number %d returns %s", sequence_number, changed_packages == null ? "null" : "a not null object"));
if (changed_packages == null) changed_packages = package_manager.getChangedPackages(0);
LogUtilities.show(this, String.format("Retrieve recently apps installs/updates using sequence number %d returns %s", sequence_number, changed_packages == null ? "null" : "a not null object"));
if (changed_packages != null)
{
List<String> packages_names = changed_packages.getPackageNames();
LogUtilities.show(this, String.format("%d recently installed/updated apps", packages_names == null ? 0 : packages_names.size()));
if (packages_names != null) for (String package_name : packages_names) PackagesUpdatedReceiver.doProcessPackageUpdate(this, new Intent(isNewInstall(package_manager, package_name) ? Intent.ACTION_PACKAGE_ADDED : Intent.ACTION_PACKAGE_REPLACED).setData(Uri.parse(String.format("package:%s", package_name))));
LogUtilities.show(this, String.format("Storing %s is the sequence number for next iteration", changed_packages.getSequenceNumber()));
ApplicationPreferences.putInteger(this, GET_CHANGED_PACKAGES_SEQUENCE_NUMBER_KEY, changed_packages.getSequenceNumber());
}
else
{
LogUtilities.show(this, String.format("Storing %s is the sequence number for next iteration", sequence_number + 1));
ApplicationPreferences.putInteger(this, GET_CHANGED_PACKAGES_SEQUENCE_NUMBER_KEY, sequence_number + 1);
}
}
catch (Exception e)
{
LogUtilities.show(this, e);
}
}
My experimental results so far have shown that this PackageManager API method getChangedPackages() is not reliable: quite often the returned ChangedPackages value contains many unchanged packages. So I’ve decided to implement a similar feature in a class called PackageUtils, as shown below. The idea is to poll for all the installed packages, as shown in method getInstalledPackageNames() below, and compare the string list with a previously saved one. This comparison boils down to comparing 2 string lists, as shown in method operate2StringLists() below. To get a set of removed packages, use GET_1_MINUS_2_OR_REMOVED as operation. To get a set of added packages, use GET_2_MINUS_1_OR_ADDED as operation.
public class PackageUtils {
public static final int GET_1_MINUS_2_OR_REMOVED = 0;
public static final int GET_2_MINUS_1_OR_ADDED = 1;
// Get all the installed package names
public static List<String> getInstalledPackageNames(Context context) {
List<String> installedPackageNames = new ArrayList<>();
try {
PackageManager packageManager = context.getPackageManager();
List<ApplicationInfo> appInfoList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo appInfo : appInfoList) {
installedPackageNames.add(appInfo.packageName);
}
} catch (Exception e) {
e.printStackTrace();
}
return installedPackageNames;
}
// Compare 2 string lists and return differences.
public static Set<String> operate2StringLists(List<String> pkgList1, List<String> pkgList2, int operation) {
Set<String> result = null;
Set<String> pkgSet1 = new HashSet<String>(pkgList1);
Set<String> pkgSet2 = new HashSet<String>(pkgList2);
switch (operation) {
case GET_1_MINUS_2_OR_REMOVED:
pkgSet1.removeAll(pkgSet2);
result = pkgSet1;
break;
case GET_2_MINUS_1_OR_ADDED:
pkgSet2.removeAll(pkgSet1);
result = pkgSet2;
break;
default:
break;
}
return result;
}
}
The code has been tested on an Android Oreo device. It can reliably detect all added and removed packages between 2 time instances. However, it can’t detect updated packages in-between.
Finally got it. You have to create a variable called sequenceNumber, and update it every time you query changed packages.
private static int sequenceNumber = 0;
...
PackageManager pm = getContext().getPackageManager();
ChangedPackages changedPackages = pm.getChangedPackages(sequenceNumber);
if(changedPackages != null)
sequenceNumber = changedPackages.getSequenceNumber();

How to check if an Activity is enabled?

Background
I'm trying to check if an activity (or any other app component type, for that matter) is enabled/disabled at runtime.
The problem
It's possible to use the next code:
final ComponentName componentName = new ComponentName(context, activityClass);
final PackageManager pm = context.getPackageManager();
final int result = pm.getComponentEnabledSetting(componentName);
But the returned result, as written on the documentation is:
Returns the current enabled state for the component. May be one of
COMPONENT_ENABLED_STATE_ENABLED, COMPONENT_ENABLED_STATE_DISABLED, or
COMPONENT_ENABLED_STATE_DEFAULT. The last one means the component's
enabled state is based on the original information in the manifest as
found in ComponentInfo.
So it's not just enabled/disabled, but also "default".
The question
If "COMPONENT_ENABLED_STATE_DEFAULT" is returned, how do I know if it's default as enabled or disabled (at runtime)?
The reason for this question is that the code should work no matter what people put in the manifest (for the "enabled" attribute) .
Is it possible perhaps to use intents resolving?
If COMPONENT_ENABLED_STATE_DEFAULT is returned, how do I know if it's default as enabled or disabled?
You will need to load all the components using PackageManager and check the enabled state for the matching ComponentInfo. The following code should work:
public static boolean isComponentEnabled(PackageManager pm, String pkgName, String clsName) {
ComponentName componentName = new ComponentName(pkgName, clsName);
int componentEnabledSetting = pm.getComponentEnabledSetting(componentName);
switch (componentEnabledSetting) {
case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
return false;
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
return true;
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
default:
// We need to get the application info to get the component's default state
try {
PackageInfo packageInfo = pm.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES
| PackageManager.GET_RECEIVERS
| PackageManager.GET_SERVICES
| PackageManager.GET_PROVIDERS
| PackageManager.GET_DISABLED_COMPONENTS);
List<ComponentInfo> components = new ArrayList<>();
if (packageInfo.activities != null) Collections.addAll(components, packageInfo.activities);
if (packageInfo.services != null) Collections.addAll(components, packageInfo.services);
if (packageInfo.providers != null) Collections.addAll(components, packageInfo.providers);
for (ComponentInfo componentInfo : components) {
if (componentInfo.name.equals(clsName)) {
return componentInfo.isEnabled();
}
}
// the component is not declared in the AndroidManifest
return false;
} catch (PackageManager.NameNotFoundException e) {
// the package isn't installed on the device
return false;
}
}
}
Testing the above code on my device:
System.out.println(isComponentEnabled(getPackageManager(),
"com.android.systemui",
"com.android.systemui.DessertCaseDream"));
System.out.println(isComponentEnabled(getPackageManager(),
"com.android.settings",
"com.android.settings.DevelopmentSettings"));
false
true
I think the field ComponentInfo.enabled means the value set in the AndroidManifest.xml file. If not specified, the default will be true. So, in the following example:
<receiver android:name=".BroadcastReceiver1"
android:enabled="false" />
<receiver android:name=".BroadcastReceiver2"
android:enabled="true" />
<receiver android:name=".BroadcastReceiver3" />
the enabled field will be false in BroadcastReceiver1, true in BroadcastReceiver2 and true in BroadcastReceiver3, while pm.getComponentEnabledSetting(componentName) will return ENABLED or DISABLED if the value in AndroidManifest is overridden or DEFAULT if not overriden
Then, according to #Jared Rummler answer if pm.getComponentEnabledSetting(componentName) returns PackageManager.COMPONENT_ENABLED_STATE_DEFAULT the actual value will be the one set in ComponentInfo.enabled field which will be the same as the one set in AndroidManifest, while ComponentInfo.isEnabled() would depend on the whole application state
EDIT: To sum up:
public static boolean isComponentEnabled(PackageManager pm, String pkgName, String clsName) {
ComponentName componentName = new ComponentName(pkgName, clsName);
int componentEnabledSetting = pm.getComponentEnabledSetting(componentName);
switch (componentEnabledSetting) {
case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
return false;
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
return true;
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
default:
// We need to get the application info to get the component's default state
try {
PackageInfo packageInfo = pm.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES
| PackageManager.GET_RECEIVERS
| PackageManager.GET_SERVICES
| PackageManager.GET_PROVIDERS
| PackageManager.GET_DISABLED_COMPONENTS);
List<ComponentInfo> components = new ArrayList<>();
if (packageInfo.activities != null) Collections.addAll(components, packageInfo.activities);
if (packageInfo.services != null) Collections.addAll(components, packageInfo.services);
if (packageInfo.providers != null) Collections.addAll(components, packageInfo.providers);
for (ComponentInfo componentInfo : components) {
if (componentInfo.name.equals(clsName)) {
return componentInfo.enabled; //This is the default value (set in AndroidManifest.xml)
//return componentInfo.isEnabled(); //Whole package dependant
}
}
// the component is not declared in the AndroidManifest
return false;
} catch (PackageManager.NameNotFoundException e) {
// the package isn't installed on the device
return false;
}
}
}
The code of Jared Rummler is good and it work but it takes the status in the manifest.
To have the current status of a component inside my app I needed to create the "ComponentName" through the "Package Context" and the "Component Class" and not the "Package Name" and "Class Name".
I had a BroadcastReceiver setted to "enabled = false" in the manifest, after that I enabled it inside my app using the package manager, but the Jared Rummler's codes always return me "STATE_ENABLED_DEFAULT" and "enabled and isEnabled()" always returned false.
Using the "Package Context" and the "Component Class" i get directly the "ENABLED_STATE_DISABLED" and "ENABLED_STATE_ENABLED" without using the code in the default part, also the "enabled and isEnabled()" returned me anyway FALSE if I've started the receiver using the package manager.
Hope this is useful, see u
public static void enableDisableComponent(Context pckg, Class componentClass, boolean enable){
ComponentName component = new ComponentName(pckg, componentClass);
if(enable == !checkIfComponentIsEnabled(pckg, componentClass)) {
pckg.getPackageManager().setComponentEnabledSetting(
component,
enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
);
}
}
public static boolean checkIfComponentIsEnabled(Context pckg, Class componentClass){
boolean ret = false;
ComponentName componentName = new ComponentName(pckg, componentClass);
int componentEnabled = pckg.getPackageManager().getComponentEnabledSetting(componentName);
switch(componentEnabled){
case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
break;
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
ret = true;
break;
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
default:
ret = checkEnabledComponentsInfo(pckg, componentClass);
break;
}
return ret;
}
private static boolean checkEnabledComponentsInfo(Context pckg, Class componentClass){
boolean ret = false;
try{
PackageInfo packageInfo = pckg.getPackageManager().getPackageInfo(
pckg.getPackageName(),
PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS |
PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS |
PackageManager.GET_DISABLED_COMPONENTS
);
List<ComponentInfo> componentsInfo = new ArrayList<>();
if(packageInfo.activities != null && packageInfo.activities.length > 0){
Collections.addAll(componentsInfo, packageInfo.activities);
}
if(packageInfo.services != null && packageInfo.services.length > 0){
Collections.addAll(componentsInfo, packageInfo.services);
}
if(packageInfo.providers != null && packageInfo.providers.length > 0){
Collections.addAll(componentsInfo, packageInfo.providers);
}
if(packageInfo.receivers != null && packageInfo.receivers.length > 0){
Collections.addAll(componentsInfo, packageInfo.receivers);
}
if(componentsInfo.size() > 0){
for(ComponentInfo info : componentsInfo){
if(info.name.equals(componentClass.getName())){
ret = info.isEnabled();
break;
}
}
}
} catch(PackageManager.NameNotFoundException nnfE){
onException(nnfE);
}
return ret;
}

How do I check if an app is a non-system app in Android?

I am getting a list of ApplicationInfo Objects with packageManager.getInstalledApplications(0) and attempting to categorize them by whether or not they are a system application.
For a while I have been using the technique described here, however after seeing that in my application, some of the apps were not in the non-system apps list (such as Facebook, which when available asks the system to install itself on the SD card). After next reading the actual documentation for ApplicationInfo.FLAG_SYSTEM, and understanding that it doesn't actually filter system apps, I am now looking for a new approach.
My guess is that there is a large gap between UIDs of System and non-system apps that I can gather to make this distinction, but as of yet I have not found an answer. I also looked into other flags, such as ApplicationInfo.FLAG_EXTERNAL_STORAGE, however I am supporting API 1.5.
Does anyone have a real solution to this (not involving FLAG_SYSTEM)?
PackageManager pm = mcontext.getPackageManager();
List<PackageInfo> list = pm.getInstalledPackages(0);
for(PackageInfo pi : list) {
ApplicationInfo ai = pm.getApplicationInfo(pi.packageName, 0);
System.out.println(">>>>>>packages is<<<<<<<<" + ai.publicSourceDir);
if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
System.out.println(">>>>>>packages is system package"+pi.packageName);
}
}
I was under the impression that all apps in the system image are system apps (and normally installed in /system/app).
If FLAG_SYSTEM is only set to system applications, this will work even for apps in external storage:
boolean isUserApp(ApplicationInfo ai) {
int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
return (ai.flags & mask) == 0;
}
An alternative is to use the pm command-line program in your phone.
Syntax:
pm list packages [-f] [-d] [-e] [-s] [-3] [-i] [-u] [--user USER_ID] [FILTER]
pm list packages: prints all packages, optionally only
those whose package name contains the text in FILTER. Options:
-f: see their associated file.
-d: filter to only show disbled packages.
-e: filter to only show enabled packages.
-s: filter to only show system packages.
-3: filter to only show third party packages.
-i: see the installer for the packages.
-u: also include uninstalled packages.
Code:
ProcessBuilder builder = new ProcessBuilder("pm", "list", "packages", "-s");
Process process = builder.start();
InputStream in = process.getInputStream();
Scanner scanner = new Scanner(in);
Pattern pattern = Pattern.compile("^package:.+");
int skip = "package:".length();
Set<String> systemApps = new HashSet<String>();
while (scanner.hasNext(pattern)) {
String pckg = scanner.next().substring(skip);
systemApps.add(pckg);
}
scanner.close();
process.destroy();
Then:
boolean isUserApp(String pckg) {
return !mSystemApps.contains(pckg);
}
You can check the signature of application which it signed with system. Like below
/**
* Match signature of application to identify that if it is signed by system
* or not.
*
* #param packageName
* package of application. Can not be blank.
* #return <code>true</code> if application is signed by system certificate,
* otherwise <code>false</code>
*/
public boolean isSystemApp(String packageName) {
try {
// Get packageinfo for target application
PackageInfo targetPkgInfo = mPackageManager.getPackageInfo(
packageName, PackageManager.GET_SIGNATURES);
// Get packageinfo for system package
PackageInfo sys = mPackageManager.getPackageInfo(
"android", PackageManager.GET_SIGNATURES);
// Match both packageinfo for there signatures
return (targetPkgInfo != null && targetPkgInfo.signatures != null && sys.signatures[0]
.equals(targetPkgInfo.signatures[0]));
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
You can get more code on my blog How to check if application is system app or not (By signed signature)
There are 2 type of Non - system applications :
Apps downloaded from Google Play Store
Preloaded apps by device manufacturer
This code will return a list of all above applications:
ArrayList<ApplicationInfo> mAllApp =
mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for(int i = 0; i < mAllApp.size(); i++) {
if((mAllApp.get(i).flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
// 1. Applications downloaded from Google Play Store
mAllApp1.add(mAllApp.get(i));
}
if((mAllApp.get(i).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
// 2. Applications preloaded in device by manufecturer
mAllApp1.add(mAllApp.get(i));
}
}
Well, it's a sloppy solution in my opinion (what if /data/app isn't the apps directory on all devices?), but after a thorough search, this is what I have come up with:
for (ApplicationInfo ai : appInfo) {
if (ai.sourceDir.startsWith("/data/app/")) {
//Non-system app
}
else {
//System app
}
}
There is a little bit of misunderstanding here. For Android the notion of a "system app" is one that is install on the system image, it says nothing about what developer it came from. So, if an OEM decides to preload Facebook on to the system image, it is a system app and will continue to be so, regardless of where updates to the app get installed. They won't get installed on the system image, for sure, because it is read-only.
So ApplicationInfo.FLAG_SYSTEM is correct, but that doesn't seem to be the question you are asking. I think you're asking if a package is signed with the system certificate. Which is not necessarily a good indicator of anything, this may vary from device to device and some surprising components on vanilla Android are not signed with the system certificate, even though you might expect them to be.
In newer versions of Android there is a new path, /system/priv-app/ that attempts to be the install location for "real" system apps. Apps that are just pre-loaded on the system image then end up in /system/app/. See AOSP Privileged vs System app
If an Application is a non-system application it must have a launch Intent by which it can be launched. If the launch intent is null then its a system App.
Example of System Apps: "com.android.browser.provider", "com.google.android.voicesearch".
For the above apps you will get NULL when you query for launch Intent.
PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo packageInfo:packages){
if( pm.getLaunchIntentForPackage(packageInfo.packageName) != null ){
String currAppName = pm.getApplicationLabel(packageInfo).toString();
//This app is a non-system app
}
}
This is a simplified and more efficient version of other responses listed here. It is more efficient if you just iterate directly over the ApplicationInfos.
List<ApplicationInfo> applications = context.getPackageManager()
.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo appInfo : applications){
if((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0){
// Not a system app
}
}
Here are different possible ways to see if the app is a system app by its package name (used some of the codes in this post)
package com.test.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Pattern;
import timber.log.Timber;
public class SystemAppChecker {
private PackageManager packageManager = null;
public SystemAppChecker(Context context) {
packageManager = context.getPackageManager();
}
/**
* Check if system app by 'pm' command-line program
*
* #param packageName
* package name of application. Cannot be null.
* #return <code>true</code> if package is a system app.
*/
public boolean isSystemAppByPM(String packageName) {
if (packageName == null) {
throw new IllegalArgumentException("Package name cannot be null");
}
ProcessBuilder builder = new ProcessBuilder("pm", "list", "packages", "-s");
Process process = null;
try {
process = builder.start();
} catch (IOException e) {
Timber.e(e);
return false;
}
InputStream in = process.getInputStream();
Scanner scanner = new Scanner(in);
Pattern pattern = Pattern.compile("^package:.+");
int skip = "package:".length();
Set<String> systemApps = new HashSet<String>();
while (scanner.hasNext(pattern)) {
String pckg = scanner.next().substring(skip);
systemApps.add(pckg);
}
scanner.close();
process.destroy();
if (systemApps.contains(packageName)) {
return true;
}
return false;
}
/**
* Check if application is preloaded.
*
* #param packageName
* package name of application. Cannot be null.
* #return <code>true</code> if package is preloaded.
*/
public boolean isSystemPreloaded(String packageName) {
if (packageName == null) {
throw new IllegalArgumentException("Package name cannot be null");
}
try {
ApplicationInfo ai = packageManager.getApplicationInfo(
packageName, 0);
if (ai.sourceDir.startsWith("/system/app/") || ai.sourceDir.startsWith("/system/priv-app/")) {
return true;
}
} catch (NameNotFoundException e) {
Timber.e(e);
}
return false;
}
/**
* Check if the app is system signed or not
*
* #param packageName
* package of application. Cannot be blank.
* #return <code>true</code> if application is signed by system certificate,
* otherwise <code>false</code>
*/
public boolean isSystemSigned(String packageName) {
if (packageName == null) {
throw new IllegalArgumentException("Package name cannot be null");
}
try {
// Get packageinfo for target application
PackageInfo targetPkgInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_SIGNATURES);
// Get packageinfo for system package
PackageInfo sys = packageManager.getPackageInfo(
"android", PackageManager.GET_SIGNATURES);
// Match both packageinfo for there signatures
return (targetPkgInfo != null && targetPkgInfo.signatures != null && sys.signatures[0]
.equals(targetPkgInfo.signatures[0]));
} catch (PackageManager.NameNotFoundException e) {
Timber.e(e);
}
return false;
}
/**
* Check if application is installed in the device's system image
*
* #param packageName
* package name of application. Cannot be null.
* #return <code>true</code> if package is a system app.
*/
public boolean isSystemAppByFLAG(String packageName) {
if (packageName == null) {
throw new IllegalArgumentException("Package name cannot be null");
}
try {
ApplicationInfo ai = packageManager.getApplicationInfo(
packageName, 0);
// Check if FLAG_SYSTEM or FLAG_UPDATED_SYSTEM_APP are set.
if (ai != null
&& (ai.flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
return true;
}
} catch (NameNotFoundException e) {
Timber.e(e);
}
return false;
}
}
if (!packageInfo.sourceDir.toLowerCase().startsWith("/system/"))
If having an APK file and want to check is it System app or User installed
a Simple logic:-
System app Files are not writable
private boolean isSystemApkFile(File file){
return !file.canWrite();
}
So I'd like to put here an utility class I made with the knowledge of this thread and a few others. But before I continue, an explanation of some terms, if I got them all right, copied from that class, which are used on it.
Below KitKat 4.4, all apps in /system/app were given privileged
permissions. Even the Calculator app had them. That could be a
security breach. So they were separated between ordinary and
privileged system apps and ordinary ones don't have privileged
permissions above KitKat 4.4. So these utilities have that in mind.
They also have in mind the following designations:
Platform-signed app: any app that is signed with the platform/system key (so they have system signature permissions), whether it is
installed on the system partitions or not.
System app: any app that is installed on the system partitions.
Updated system app: any system app that was updated (meaning now it is also installed on /data/app).
Privileged system app: below KitKat 4.4, any app installed on /system/app; from KitKat 4.4 onwards, only the apps installed on
/system/priv-app (I really mean only /system). These apps have
privileged permissions.
Ordinary system app: only as of KitKat 4.4, those without privileged permissions, even though they're still system apps. Below KitKat 4.4,
they're non-existent.
System partition notes: until Oreo 8.1, there
was only one: /system. As of Pie (9), there is also /vendor and
/product.
So with that in mind, here are 2 functions:
/**
* <p>Checks if an app is installed on the system partitions and was updated.</p>
*
* #param applicationInfo an instance of {#link ApplicationInfo} for the package to be checked
*
* #return true if it is, false otherwise
*/
private static boolean isUpdatedSystemApp(#NonNull final ApplicationInfo applicationInfo) {
return (applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
}
/**
* <p>Checks if an app is installed in the system partitions (ordinary app or privileged app, doesn't matter).</p>
*
* #param applicationInfo an instance of {#link ApplicationInfo} for the package to be checked
*
* #return true if it is, false otherwise
*/
private static boolean isSystemApp(#NonNull final ApplicationInfo applicationInfo) {
// Below Android Pie (9), all system apps were in /system. As of Pie, they can ALSO be in /vendor and /product.
boolean ret_value = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// FLAG_SYSTEM checks if it's on the system image, which means /system. So to check for /vendor and
// /product, here are 2 special flags.
ret_value = ret_value || (applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
ret_value = ret_value || (applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
}
return ret_value;
}
To check if an app is a privileged system app or is ordinary system app, and/or is signed with the platform/system key, I'll leave 3 functions below. I believe it's off-topic to the question, but I'll put it in case anyone like me needed it.
/**
* <p>Checks if an app is an ordinary system app (installed on the system partitions, but no privileged or signature
* permissions granted to it).</p>
* <p>Note: will return false for any app on KitKat 4.4 and below.</p>
*
* #param applicationInfo an instance of {#link ApplicationInfo} for the package to be checked
*
* #return true if it is, false otherwise
*/
private static boolean isOrdinarySystemApp(#NonNull final ApplicationInfo applicationInfo) {
// It's an ordinary system app if it doesn't have any special permission privileges (it's not a Privileged app
// nor is it signed with the system key).
boolean ret_value = isSystemApp(applicationInfo) && !hasPrivilegedPermissions(applicationInfo);
final boolean signed_system_key = hasSystemSignaturePermissions(applicationInfo);
ret_value = ret_value && signed_system_key;
return ret_value;
}
/**
* <p>Checks if an app has signature permissions - checks if it's signed with the platform/system certificate by
* comparing it to the "android" package.</p>
* <br>
* <p>ATTENTION: if the chosen app was signed multiple times and the system is running below Android Pie, this check
* may return false wrongly, since it checks if ALL the signatures from the "android" package and the chosen
* application match. If at least one doesn't match in both, this will return false. So use with caution in case of
* multiple signers. With only one signer, it's all right.</p>
*
* #param applicationInfo an instance of {#link ApplicationInfo} for the package to be checked
* #return true if it is, false otherwise
*/
private static boolean hasSystemSignaturePermissions(#NonNull final ApplicationInfo applicationInfo) {
// If on Pie or above, check with a private flag (appeared on Pie only).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return (applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY) != 0;
}
// Else, check by comparing signatures of a platform-signed app and the chosen app.
return UtilsGeneral.getContext().getPackageManager().checkSignatures(applicationInfo.packageName, "android")
== PackageManager.SIGNATURE_MATCH;
}
/**
* <p>"Value for {#link ApplicationInfo#flags}: set to {#code true} if the application
* is permitted to hold privileged permissions.</p>
*
* {#hide}"
* <p>NOTE: Only on API 19 through API 22.</p>
*/
private static final int FLAG_PRIVILEGED = 1 << 30;
/**
* <p>Checks if an app is a Privileged App.</p>
* <p>Note: will return true for any system app below KitKat 4.4.</p>
*
* #param applicationInfo an instance of {#link ApplicationInfo} for the package to be checked
*
* #return true if it is, false otherwise
*/
private static boolean hasPrivilegedPermissions(#NonNull final ApplicationInfo applicationInfo) {
// Check if it's an app installed in the system partitions. If it is, check with methods that apply only to
// apps installed on the system partitions.
if (isSystemApp(applicationInfo)) {
// If it's below KitKat 4.4 and it's a system app, it's a privileged one automatically.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return true;
}
// If on Marshmallow or above, check with a private flag.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
return true;
}
}
// If between KitKat 4.4 and Lollipop 5.1, use a deleted flag.
if ((applicationInfo.flags & FLAG_PRIVILEGED) != 0) {
return true;
}
}
// In case none returned true above, the app may still be signed with the platform/system's key, which will
// grant it exactly all permissions there are (which includes privileged permissions - ALL permissions).
return hasSystemSignaturePermissions(applicationInfo);
}
If you want, you can join this last one to the ones above, but I don't really recommend it. It will only work work as long as the system app hasn't been updated.
/**
* <p>Gets a list of folders a system app might be installed in, depending on the device's Android version.</p>
* <p>Note that an updated system app will report as being installed in /data/app. For these locations to be
* checked, the app must not have been updated. If it has, it's not possible to tell using the directory, I think.</p>
*
* #param privileged_app true if it's to return a list for privileged apps, false if it's for ordinary system apps,
* null if it's to return a list for both types
*
* #return a list of folders its APK might be in
*/
#NonNull
private static String[] getAppPossibleFolders(#Nullable final Boolean privileged_app) {
final Collection<String> ret_folders = new ArrayList<>(5);
final String PRIV_APP_FOLDER = "/system/priv-app";
final String ORD_APP_SYSTEM_FOLDER = "/system/app";
final String ORD_APP_VENDOR_FOLDER = "/vendor/app";
final String ORD_APP_PRODUCT_FOLDER = "/product/app";
if (privileged_app == null) {
ret_folders.add(PRIV_APP_FOLDER);
ret_folders.add(ORD_APP_SYSTEM_FOLDER);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ret_folders.add(ORD_APP_VENDOR_FOLDER);
ret_folders.add(ORD_APP_PRODUCT_FOLDER);
}
} else if (privileged_app) {
ret_folders.add(PRIV_APP_FOLDER);
} else {
ret_folders.add(ORD_APP_SYSTEM_FOLDER);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ret_folders.add(ORD_APP_VENDOR_FOLDER);
ret_folders.add(ORD_APP_PRODUCT_FOLDER);
}
}
// Leave it in 0 size allocation. Or null values will appear, and I don't want to need to be careful about it.
return ret_folders.toArray(new String[0]);
/*
Use with:
// If it's an updated system app, its APK will be said to be in /data/app, and the one on the system partitions
// will become unused. But if it's not updated, it's all fine and the APK path can be used to check if it's
// a privileged app or not.
if (!isUpdatedSystemApp(applicationInfo)) {
for (final String folder : getAppPossibleFolders(false)) {
if (applicationInfo.sourceDir.startsWith(folder)) {
return true;
}
}
}
*/
}
Here is an AppUtil I wrote for that purpose.
Usage example:
new AppsUtil(this).printInstalledAppPackages(AppsUtil.AppType.USER);
AppsUtil.java
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
public class AppsUtil
{
public static final String TAG = "PackagesInfo";
private Context _context;
private ArrayList<PckgInfo> _PckgInfoList;
public enum AppType
{
ALL {
#Override
public String toString() {
return "ALL";
}
},
USER {
#Override
public String toString() {
return "USER";
}
},
SYSTEM {
#Override
public String toString() {
return "SYSTEM";
}
}
}
class PckgInfo
{
private AppType appType;
private String appName = "";
private String packageName = "";
private String versionName = "";
private int versionCode = 0;
private void prettyPrint()
{
Log.i(TAG, appName + "\n AppType: " + appType.toString() + "\n Package: " + packageName + "\n VersionName: " + versionName + "\n VersionCode: " + versionCode);
}
}
public AppsUtil(Context context)
{
super();
this._context = context;
this._PckgInfoList = new ArrayList<PckgInfo>();
}
public void printInstalledAppPackages(AppType appType)
{
retrieveInstalledAppsPackages();
Log.i(TAG, "");
for (int i = 0; i < _PckgInfoList.size(); i++)
{
if (AppType.ALL == appType)
{
_PckgInfoList.get(i).prettyPrint();
}
else
{
if (_PckgInfoList.get(i).appType == appType)
_PckgInfoList.get(i).prettyPrint();
}
}
}
public ArrayList<PckgInfo> getInstalledAppPackages(AppType appType)
{
retrieveInstalledAppsPackages();
ArrayList<PckgInfo> resultPInfoList = new ArrayList<PckgInfo>();
if (AppType.ALL == appType)
{
return _PckgInfoList;
}
else
{
for (int i = 0; i < _PckgInfoList.size(); i++)
{
if (_PckgInfoList.get(i).appType == appType)
resultPInfoList.add(_PckgInfoList.get(i));
}
return resultPInfoList;
}
}
private void retrieveInstalledAppsPackages()
{
PackageManager pm = _context.getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
for (PackageInfo pi : packs)
{
try
{
PckgInfo newInfo = new PckgInfo();
ApplicationInfo ai = pm.getApplicationInfo(pi.packageName, 0);
newInfo.appType = getAppType(ai);
newInfo.appName = pi.applicationInfo.loadLabel(pm).toString();
newInfo.packageName = pi.packageName;
newInfo.versionName = pi.versionName;
newInfo.versionCode = pi.versionCode;
_PckgInfoList.add(newInfo);
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
}
}
AppType getAppType(ApplicationInfo ai)
{
AppType resultType ;
if (isUserApp(ai))
resultType = AppType.USER;
else
resultType = AppType.SYSTEM;
return resultType;
}
boolean isUserApp(ApplicationInfo ai)
{
int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
return (ai.flags & mask) == 0;
}
}
You can use checkSignatures to determine if an app is a system app or not.
All system apps are signed with the same key.
https://developer.android.com/reference/android/content/pm/PackageManager#checkSignatures(java.lang.String,%20java.lang.String)
And signed with the system key is the "android" package.
val checkPackage: String = "com.package.to.check"
val systemPackageName = "android"
if (packageManager.checkSignatures(systemPackageName, checkPackage) == PackageManager.SIGNATURE_MATCH) {
Log.d("TUT", "System app")
} else {
Log.d("TUT", "Non-System app")
}

Get active Application name in Android

I am trying to make a program that shows all the active applications.
I searched everywhere but could only find code that shows the package name only.
It would be of great help if you masters can tell me how to display all the active application name
Did you try using ActivityManager.getRunningAppProcesses()?
Here is the sample code for retrieving names:ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
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
}
}
If you are getting the package name, you should be able to get additional information about the application using the PackageManager:
http://developer.android.com/reference/android/content/pm/PackageManager.html
There are direct methods for getting the application icon, ApplicationInfo and ActivityInfo objects. Off the top of my head I don't know which one would direct you to the readable name, but if its not directly accessible through one of the methods here, it should be accessible from the application resources (also accessible from this class).
If you are writing a service and want to update the current "foreground app" at regular intervals like I did, DO NOT be tempted to get the ActivityManager instance in the onCreate() of your service and re-use it when updating the current app name:
public class MyService extends Service implements {
ActivityManager mActivityManager;
#Override public void onCreate() {
mActivityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE ); }
String getForegroundAppName() {
String appname;
List <RunningAppProcessInfo> l;
l = mActivityManager.getRunningAppProcesses();
while( i.hasNext() ) {
if ( info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && !isRunningService(info.processName) {
currentApp = info;
break;
}
}
if ( currentApp != null ) {
try {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(currentApp.processName, PackageManager.GET_META_DATA ));
appname = c.toString();
}
return appname;
}
}
Don't do this. It causes a memory leak resulting in numerous GC_CONCURRENT errors every time it's called. I don't know the real reason behind this but it's much cleaner to get the ApplicationManager instance each time you use it like this:
public class MyService extends Service implements {
#Override public void onCreate() {... }
String getForegroundAppName() {
ActivityManager mActivityManager;
String appname;
mActivityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE );
List <RunningAppProcessInfo> l;
l = mActivityManager.getRunningAppProcesses();
while( i.hasNext() ) {
if ( info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && !isRunningService(info.processName) {
currentApp = info;
break;
}
}
if ( currentApp != null ) {
try {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(currentApp.processName, PackageManager.GET_META_DATA ));
appname = c.toString();
}
return appname;
}
}

Categories

Resources