Giter Site home page Giter Site logo

ricvalerio / foregroundappchecker Goto Github PK

View Code? Open in Web Editor NEW
190.0 19.0 51.0 111 KB

Foreground application detection library for android.

License: Apache License 2.0

Java 100.00%
android android-library android-development library foreground foreground-detection

foregroundappchecker's Introduction

Foreground App Checker for android

This library tries to provide an easy way to get the foreground application package name. It uses different techniques, adequate to the device's android version.

Download

Download

apply plugin: 'com.android.application'

repositories {
    // ...
    maven { url 'https://dl.bintray.com/rvalerio/maven' }
}

dependencies {
    // ...
    compile 'com.rvalerio:fgchecker:1.1.0'
}

Setup

To use this library, you will need to request permissions in order to support different versions.

To support ICS until Lollipop, you need to request android.permission.GET_TASKS permission.

To support Lollipop or above, you need to request android.permission.PACKAGE_USAGE_STATS permission.

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />

For your convenience, I provide here code to request usage stats permission:

    
void requestUsageStatsPermission() {
    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP 
        && !hasUsageStatsPermission(this)) {
        startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
    }
}

@TargetApi(Build.VERSION_CODES.KITKAT)
boolean hasUsageStatsPermission(Context context) {
    AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow("android:get_usage_stats",
            android.os.Process.myUid(), context.getPackageName());
    boolean granted = mode == AppOpsManager.MODE_ALLOWED;
    return granted;
}

Usage

In it's simplest form, and to get the package name of the foreground application, you can do like so:

AppChecker appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp(context);

If you would like to have this being checked on an interval, you can do like so:

AppChecker appChecker = new AppChecker();
appChecker
    .whenAny(new AppChecker.Listener() {
        @Override
        public void onForeground(String packageName) {
            // do something
        }
    )
    .timeout(1000)
    .start(this);

If you want to check for specific package names, it also provides a way to do so:

AppChecker appChecker = new AppChecker();
appChecker
    .when("com.other.app", new AppChecker.Listener() {
        @Override
        public void onForeground(String packageName) {
            // do something when com.other.app is in the foreground
        }
    )
    .when("com.my.app", new AppChecker.Listener() {
        @Override
        public void onForeground(String packageName) {
            // do something when com.my.app is in the foreground
        }
    )
    .whenOther(new AppChecker.Listener() {
        @Override
        public void onForeground(String packageName) {
            // do something when none of the registered packages are in the foreground
        }
    )
    .whenAny(new AppChecker.Listener() {
        @Override
        public void onForeground(String packageName) {
            // do something everytime a scan for foreground app is run
        }
    )
    .timeout(1000)
    .start(this);

Callbacks are done on the UI thread. Keep in mind that callbacks are done every time there is a scan. Currently it does not do callbacks only when the foreground app changes.

Upcoming features

  • Add option to only callback when there is a package name change

This library is distributed under the Apache 2.0 license.

License

Copyright 2016 Ricardo Valério

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

foregroundappchecker's People

Contributors

ricvalerio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

foregroundappchecker's Issues

packageName returns null after 1 hour

AppChecker mAppChecker = new AppChecker();
foreground_app_package_name = mAppChecker.getForegroundApp(mContext);

 I am  using the above code to get the foreground app name from service in background. The code works fine till 60 minutes and at 61 minutes it gives null value at foreground_app_package_name .

[DEPRECATED] Android Studio

I would ask you to migrate the library and sample app to Android Studio 3.5.1
The project is so old :( and thank you for understanding

Issue with Jcenter

Android recommended to remove jcenter library if I am going to do that I am not able to download your dependency

Context Crashes the App on library call

I am trying the sample on my android app
I try using this

        AppChecker appChecker = new AppChecker();
        String packageName = appChecker.getForegroundApp(ctx);

I tried making a context ctx
Not sure which way I am suppose to call it for it to work with your library.

so far I tried
Context ctx = getApplicationContext();
and
Context ctx = getBaseContext();

Both of them crash the app when it runs the sample code.

I downloaded the library from the download link on github project
I added the .aar library to my project
fgchecker-1.0.1.aar
I added the dependency to my project
and I import
import com.rvalerio.fgchecker.AppChecker;

Service killed with FG Checker callbacks?

I am using this library to allow the user to monitor his/her usage on each app of their phone. For that reason, I've set up callbacks in a continuous service; however, the service is killed on its own.

https://stackoverflow.com/questions/51460417/why-does-android-keep-killing-my-service

I have posted some more details on a stack overflow question, but it seems as though the fgchecker process is getting killed even though it has calbacks to the service. Any thoughts?

context error

AppChecker appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp(context);

When I try using the above the context is giving an error. Could anyone help me out with this?

Android N

Is this library should work on android N ?

needsUsageStatsPermission from sample appears to not be working as expected on 7.1

I am using this snippet of yours inside of a service, but I always get null as a package name. Testing on Google Pixel, Android version 7.1

AppChecker appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp(context);

My permissions look like this:

<uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>

appChecker.getForegroundApp() error

When trying to run your code example:

AppChecker appChecker = new AppChecker();
String packageName = appChecker.getForegroundApp();

I get the error:

Error:(54, 40) error: method getForegroundApp in class AppChecker cannot be applied to given types;
required: Context
found: no arguments
reason: actual and formal argument lists differ in length

[BUG] Android 8+ service stops

The way you start service is killed by OS after 20 seconds
Please have a lecture: https://developer.android.com/about/versions/oreo/background
Use startForegroundService() method instead of startService().

 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ctx.startForeground(NOTIFICATION_ID, mBuilder.build());
        } else {
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(ctx);
            notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }

...

foregroundappchecker-SDK

hello,
thanks for the class. look very simple to use.
I just want to ask, i cannot use sdk 26 - max 25, there is any way to use this class in older sdk then 26?
thanks.
roey

packageName returns null

AppChecker appChecker = new AppChecker();
        appChecker.whenAny(new AppChecker.Listener() {
                    @Override
                    public void onForeground(String packageName) {
                        Log.d("foreground: ", "" + packageName);
                    }
                }).timeout(1000)

packageName always give me null.
Im calling the code inside a service,

TIA.

java.lang.NullPointerException

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.List java.util.concurrent.ScheduledExecutorService.shutdownNow()' on a null object reference
at com.rvalerio.fgchecker.AppChecker.stop(SourceFile:66)

error in PreLollipopDetector

Hi!

First of all, thank you for your effort. The Library is good. And it will be better if you can fix the bugs below:

The PreLollipopDetector wont work. First of all, the must be declared in manifest, else activityManager.getRunningTasks(1) will throw a SecurityException.

Second error:
Still in the PreLollipopDetector.java. You have to assign the foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString() to the foreGroundApp variable else the method will be always return null.

Best Regards!

Zoltan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.