import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class MyBackGroundService extends Service {
private static MyBackGroundService sMyService;
private Handler handler;
@Override
public void onCreate() {
super.onCreate();
sMyService = this;
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
printCurrentTask();
handler.postDelayed(this,60);
}
},60);
}
public IBinder onBind(Intent intent) {
return null;
}
public static String getForegroundPackageName() {
return foregroundPackageName;
}
private String printCurrentTask() {
String currentApp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager)this.getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.d("Top App ******", "Current Top Running App is: " + currentApp);
return currentApp;
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(null);
}
}
add this permision for Usage stats
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions"/>
even you to ask user to enable the permision if not enabled it will not work
import android.app.AppOpsManager;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Intent backGroundService;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backGroundService = new Intent(MainActivity.this, MyBackGroundService.class);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkIfAppUsageAccess();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
void checkIfAppUsageAccess(){
boolean granted = false;
AppOpsManager appOps = (AppOpsManager) this
.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), getPackageName());
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = (checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
} else {
granted = (mode == AppOpsManager.MODE_ALLOWED);
}
if (Build.VERSION.SDK_INT >= 21 && !granted) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats == null || stats.isEmpty()) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
} else {
startService(backGroundService);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(backGroundService);
}
}
This code will work for android lollipop as well as below versions