How to get application name on various Android device? - android

I am using bellow code to get application name in Android. For example on Galaxy S4; if the phone is in Home screen, and the below function returns the TouchWiz home. However, on Note 4, the function returns Google Home. Do we have any way to maintain the application name or detect the name depending on the device name? Currently, I save the Home screen in a list corresponding to the device name. However, I think it will not cover all possible case.
public String getAppName() {
String foregroundProcess = "";
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
String topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
foregroundProcess = topPackageName;
}
}
} else {
#SuppressWarnings("deprecation")
ActivityManager.RunningTaskInfo foregroundTaskInfo = activityManager.getRunningTasks(1).get(0);
foregroundProcess = foregroundTaskInfo.topActivity.getPackageName();
}
//Convert package name to application name
final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(foregroundProcess, 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
return applicationName;
}

Related

How Do "App Lock" app work internally?

I need to develop app just like android App lock that opens password activity when app assigned application get launch. I have read below question but didn't find proper solution.
I just want to ask that what service or method they are using? how to know about any other app launch event?
In my current implementation, I have added a service and in MyService, I have added a timer to check currentApp and then I am comparing current app to assigned app.
I don't like this approach because timer takes lot of battery as well as device get slow.
public void isForeground(String myPackage){
String currentApp="";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) 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) getBaseContext().getSystemService(ACTIVITY_SERVICE);
currentApp = am.getRunningTasks(1).get(0).topActivity .getPackageName();
}
processCurrentApp(currentApp,myPackage);
}
Any one can help me in this? Thanks in advance.
To get current active apps try
public boolean isConcernedAppIsInForeground() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(5);
if (Build.VERSION.SDK_INT <= 20) {
if (task.size() > 0) {
ComponentName componentInfo = task.get(0).topActivity;
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (componentInfo.getPackageName().equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
} else {
String mpackageName = manager.getRunningAppProcesses().get(0).processName;
UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
Log.d(TAG,"isEmpty Yes");
mpackageName = "";
}else {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
Log.d(TAG,"isEmpty No : "+mpackageName);
}
}
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (mpackageName.equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
return false;
}
Check this open source project: https://github.com/amitshekhariitbhu/AppLock/

How to run broadcast receiver for every one hour?

I have created broadcast receiver inside Service and this broadcast receiver is running frequently .but i want run this broadcast receiver for every one hour.without disturbing service .any suggestion?
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
AppLockApplication.getInstance().getlocationprovider().connect();
telephonyManager.listen(null, PhoneStateListener.LISTEN_CALL_STATE);
siminfoMap = SimInfo.getSimInfo(telephonyManager,getApplicationContext());
Log.e(TAG,"-----SIM INFO STATUS------\n");
for (String keyvalue : siminfoMap.keySet()){
Log.i(TAG,"SimInfo : "+keyvalue +" : "+siminfoMap.get(keyvalue));
}
Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
HealthModel healthModel=new HealthModel();
healthinfo_Map = new HashMap<String, JSONObject>();
//Bettary status
int level= batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
int plugged= batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
boolean present= batteryStatus.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
int scale= batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
int status= batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,0);
String technology= batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
int temperature= batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
int voltage= batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
int remaing = -1;
if (level >= 0 && scale > 0) {
remaing =scale-level;
}
Log.e(TAG,"-----BATTERY STATUS-----\n");
batteryinfoMap= new HashMap<String, String>();
batteryinfoMap.put("Plugged",String.valueOf(plugged));
batteryinfoMap.put("Present",String.valueOf(present));
batteryinfoMap.put("Battaery Present Percentage", String.valueOf(level));
batteryinfoMap.put("Battaery Remaining Percentage", String.valueOf(remaing));
batteryinfoMap.put("Battaery Total Percentage", String.valueOf(scale));
for (String keyset : batteryinfoMap.keySet()){
Log.i(TAG,"Battery Info : "+keyset+" : "+batteryinfoMap.get(keyset));
}
if(status==1){
batteryinfoMap.put("Charging Status","Unknown");
}else if(status==2){
batteryinfoMap.put("Charging Status","Charging");
}else if(status==3){
batteryinfoMap.put("Charging Status","Discharging");
}else if(status==4){
batteryinfoMap.put("Charging Status","Not Charging");
}else if(status==5){
batteryinfoMap.put("Charging Status","Full");
}
batteryinfoMap.put("Temperature",String.valueOf(temperature));
batteryinfoMap.put("Technology",technology );
batteryinfoMap.put("Voltage",String.valueOf(voltage));
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//Memory status
memoryInfo = new ActivityManager.MemoryInfo();
manager.getMemoryInfo(memoryInfo);
memory_info = new HashMap<String,String>();
memory_info.put(" AvailableMemory",String.valueOf(memoryInfo.availMem ));
memory_info.put(" LowMemory",String.valueOf(memoryInfo.lowMemory));
memory_info.put(" threshold",String.valueOf(memoryInfo.threshold));
memory_info.put(" Totalmemory",String.valueOf(memoryInfo.totalMem));
Log.e(TAG,"-----RAM STATUS-----\n");
for (String keyString : memory_info.keySet()){
Log.i(TAG,"Memory Info : "+keyString +" :"+memory_info.get(keyString));
}
//External memory info :
extrenal_memory = new HashMap<String,String>();
Log.e(TAG,"-----EXTERNAL MEMORY STATUS-----\n");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
long tot=(long)stat.getBlockSizeLong()*(long)stat.getBlockCountLong();
extrenal_memory.put("Totalsize",String.valueOf(tot));
extrenal_memory.put("Availablesize",String.valueOf(bytesAvailable));
for (String keyset : extrenal_memory.keySet()){
Log.i(TAG,"External Memory : "+keyset+" : "+extrenal_memory.get(keyset));
}
}else {
Log.i(TAG,"No SD card");
}
//Internal memory info :
internal_memory = new HashMap<String,String>();
Log.e(TAG,"-----INTERNAL MEMORY STATUS-----\n");
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSizeLong();
long availableBlocks = stat.getAvailableBlocksLong();
long totalBlocks = stat.getBlockCountLong();
long avilablemem=(availableBlocks*blockSize);
long totalmem=(totalBlocks*blockSize);
internal_memory.put("Totalsize",String.valueOf(totalmem));
internal_memory.put("Availablesize",String.valueOf(avilablemem));
for (String keyset : internal_memory.keySet()){
Log.i(TAG,"Internal Memory : "+keyset+" : "+internal_memory.get(keyset));
}
InfoMap = new HashMap<String, String>();
// WIFI status
if(wifiInfo.getType() == ConnectivityManager.TYPE_MOBILE){
InfoMap.put("Wifi Type","Mobile Wifi Connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_WIFI){
InfoMap.put("Wifi Type","WIFI data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_WIMAX){
InfoMap.put("Wifi Type"," WiMAX data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_ETHERNET){
InfoMap.put("Wifi Type","Ethernet data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_BLUETOOTH){
InfoMap.put("Wifi Type","Bluetooth data connection");
}else {
InfoMap.put("Wifi Type","Other NewWork");
}
InfoMap.put("Wifi-Roaming",String.valueOf(wifiInfo.isRoaming()));
InfoMap.put("Wifi-SignalInfo",String.valueOf(wifiInfo.isAvailable()));
InfoMap.put("Wifi-State",String.valueOf(wifiInfo.getState()));
//Mobile status :
if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("EDGE")){
InfoMap.put("MobileType","2G");
}else if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSDPA")||String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSPA")|| String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSPAP")){
InfoMap.put("MobileType","3G");
}else if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("LTE") ){
InfoMap.put("MobileType","4G");
}else{
InfoMap.put("MobileType",String.valueOf(mobileInfo.getSubtypeName()));
}
InfoMap.put("Mobile-Roaming",String.valueOf(mobileInfo.isRoaming()));
InfoMap.put("Mobile-SignalInfo",String.valueOf(mobileInfo.isRoaming()));
InfoMap.put("Mobile-State",String.valueOf(mobileInfo.getState()));
Log.e(TAG,"-----CONNECTION STATUS-----\n");
for (String keyval : InfoMap.keySet()){
Log.i(TAG,"Connection : "+keyval+" :"+InfoMap.get(keyval));
}
Map<String, String> wifiDetails = DisplayWifiState();
Log.e(TAG,"-----WIFI DETAILS-----\n");
for (String keywifival : wifiDetails.keySet()){
Log.i(TAG,"WIFI details : "+keywifival+" : "+wifiDetails.get(keywifival));
}
//Installed Apps :
PackageManager pm = context.getPackageManager();
List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.SIGNATURE_MATCH);
Log.e(TAG,"INSTALLED Apps size : "+apps.size());
installapp_map = new HashMap<String,String>();
Log.e(TAG,"-----INSTALLED APPS-----\n");
for (PackageInfo rInfo :apps) {
Log.i(TAG,"Installed Apps : "+rInfo.packageName+" : "+rInfo.applicationInfo.loadLabel(pm).toString());
installapp_map.put(rInfo.packageName, rInfo.applicationInfo.loadLabel(pm).toString());
}
runningAppProcessInfo=searchRunningAppProcesses();
healthModel.setRunningprocessInfo(new JSONObject(runningAppProcessInfo));
NetInfo netInfo = new NetInfo(context);
inetaddrinfo = netInfo.getIPAddress();
if(!(String.valueOf(wifiInfo.getState()).equalsIgnoreCase("connected"))){
if(inetaddrinfo !=null) {
for (String keyString : inetaddrinfo.keySet()) {
Log.e(TAG, "Internet : " + keyString + " :" + inetaddrinfo.get(keyString));
}
}else {
Log.e(TAG,"Internet : "+"NO");
}
}else
{
// for (String keyString : inetaddrinfo.keySet()) {
// Log.e(TAG, "Internet : " + keyString + " :" + inetaddrinfo.get(keyString));
// }
}
//Current Apps:
currnt_task_map = new HashMap<String, String>();
List<ActivityManager.RunningTaskInfo> infos = manager.getRunningTasks(Integer.MAX_VALUE);
PackageManager pack=context.getPackageManager();
Log.e(TAG,"-----CURRENT APP-----\n");
String currentApp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
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();
String currentAppName="";
try {
currentAppName = (String) pack.getApplicationLabel(pack.getApplicationInfo(currentApp, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG,"Current App : "+currentApp+" : "+currentAppName);
currnt_task_map.put(currentApp,currentAppName);
}
}
}else {
for (ActivityManager.RunningTaskInfo info :infos) {
String packageName = info.topActivity.getPackageName();
String appName="";
try {
appName = (String) pack.getApplicationLabel(pack.getApplicationInfo(packageName,PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG,"Current App : "+packageName+" :"+appName );
currnt_task_map.put(packageName,appName);
}
}
//Recently used apps :
recent_task_map = new HashMap<String, String>();
Log.e(TAG,"-----RECENT APPS-----\n");
PackageManager recpack=context.getPackageManager();
List<ActivityManager.RecentTaskInfo> recentTasks = manager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_WITH_EXCLUDED);
String Recentapp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
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()) {
Recentapp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
String RecentAppName = "";
try {
RecentAppName = (String) recpack.getApplicationLabel(recpack.getApplicationInfo(Recentapp, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG, "Recent Apps : " + Recentapp + " : " + RecentAppName);
recent_task_map.put(Recentapp, RecentAppName);
}
}
}
}else {
for (ActivityManager.RecentTaskInfo task : recentTasks) {
Intent baseIntent = task.baseIntent;
if (baseIntent != null) {
String text = baseIntent.getComponent().getPackageName();
String appName = "";
try {
appName = (String) pack.getApplicationLabel(pack.getApplicationInfo(text, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG, "Recent Apps : " + text + " :" + appName);
recent_task_map.put(text,(String) appName);
}else {
Log.i(TAG,"RecentTask :"+" No Recent task");
}
}
}
//Location info :
location_info = new HashMap<String,String>();
double Latitude=AppLockApplication.getInstance().getlocationprovider().getLocation().getLatitude();
double Longitude=AppLockApplication.getInstance().getlocationprovider().getLocation().getLongitude();
Log.e(TAG,"-----LOCATION-----");
location_info.put("Latitude",String.valueOf(Latitude));
location_info.put("Longitude",String.valueOf(Longitude));
for (String keyset : location_info.keySet()){
Log.i(TAG,"Location info : "+keyset+" : "+location_info.get(keyset));
}
if(siminfoMap !=null){
healthModel.setSiminfo(new JSONObject(siminfoMap));
}
healthModel.setWifideatils(new JSONObject(wifiDetails));
healthModel.setConectivityInfo(new JSONObject(InfoMap));
healthModel.setBatteryInfo(new JSONObject(batteryinfoMap));
healthModel.setMemoreyInfo(new JSONObject(memory_info));
healthModel.setInstallAppInfo(new JSONObject(installapp_map));
healthModel.setLocationinfo(new JSONObject(location_info));
healthModel.setInternalmemory(new JSONObject(internal_memory));
if (extrenal_memory !=null) {
healthModel.setExternalmemoryinfo(new JSONObject(extrenal_memory));
}
if(inetaddrinfo !=null){
healthModel.setinetaddress(new JSONObject(inetaddrinfo));
}
healthModel.setCurTaskInfo(new JSONObject(currnt_task_map));
healthModel.setRecentTaskInfo(new JSONObject(recent_task_map));
if(siminfoMap !=null){
healthinfo_Map.put("SIMINFORMATION",healthModel.getSiminfo());
}
healthinfo_Map.put("BATTERYINFO", healthModel.getBatteryInfo());
healthinfo_Map.put("WIFIDETAILS", healthModel.getConectivityInfo());
healthinfo_Map.put("WIFIINFO", healthModel.getWifideatils());
healthinfo_Map.put("MEMORYINFO", healthModel.getMemoreyInfo());
healthinfo_Map.put("INSTALLAPPINFO",healthModel.getInstallAppInfo());
healthinfo_Map.put("RUNNINGAPPINFO", healthModel.getRunningprocessInfo());
healthinfo_Map.put("CURRTASKINFO", healthModel.getCurTaskInfo());
healthinfo_Map.put("RECENTTASKINFO", healthModel.getRecentTaskInfo());
healthinfo_Map.put("INETADDRESS", healthModel.getinetaddress());
healthinfo_Map.put("LOCATION",healthModel.getLocationinfo());
healthinfo_Map.put("INTERNALMEMORY",healthModel.getInternalmemory());
healthinfo_Map.put("EXTERNALMEMORY",healthModel.getExternalmemoryinfo());
jsonObject=new JSONObject(healthinfo_Map);
healthinfo_Map=null;
healthModel=null;
siminfoMap=null;
wifiDetails=null;
InfoMap=null;
batteryinfoMap=null;
memory_info=null;
installapp_map=null;
location_info=null;
internal_memory=null;
extrenal_memory=null;
inetaddrinfo=null;
currnt_task_map=null;
recent_task_map=null;
jsonObject=null;
runningAppProcessInfo=null;
}
};
Use AlarmManager which runs ever 1 hour to start broadcast reciever
public int setAlarm() {
Calendar Calendar_Object = Calendar.getInstance();
Intent myIntent = new Intent(Splash.this, mBatInfoReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long wkupTime = Calendar_Object.getTimeInMillis() + 36000;
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, wkupTime ,3600000, pendingIntent);
return 0;
}
Check here
Use AlarmManager for this purpose
https://developer.android.com/training/scheduling/alarms.html
You can use handler for setting time to call receiver inside of
service. Try the following code:
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run() {
//you can call your broadcast receiver here
}
};
timer.schedule(hourlyTask, 01, 1000 * 1 * 60 * 60);

How to get package name after lollipop version in android

I have tried this below code for getting forground application package name but it is getting my own app application package name only. other application packagte name will be null.it means it is returning null ...how can i get package name.. is there any other way. I know getrunningappprocess is blocked by google.
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<ActivityManager.RunningAppProcessInfo> tasks = manager.getRunningAppProcesses();
String mpackageName = tasks.get(0).processName;
UsageStatsManager usage = (UsageStatsManager) this.getSystemService(this.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!runningTask.isEmpty() && runningTask != null) {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
}
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
Log.e("AppCheck", "comfor2 : " + mpackageName + " pak2 : " + pakageName.get(i));
if (mpackageName.equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
Get class name from below method...
public static void classNameRunning(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
// print log for class name
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
Log.w("Package name ==> ",componentInfo.getPackageName());
}
}
}
public static HashSet<String> getRunningApps(Context context) {
final HashSet<String> hashSet = new HashSet<String>();
final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final PackageManager packageManager = context.getPackageManager();
List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo runningTaskInfo : runningTasks) {
String packageName = runningTaskInfo.baseActivity.getPackageName();
try {
String appName = packageManager.getApplicationInfo(packageName, 0).loadLabel(packageManager).toString();
hashSet.add(appName);
} catch (NameNotFoundException exception) {
// handle Exception
}
}
return hashSet;
}

How to `getTopActivity` name or get currently running application package name in lollipop?

I am creating a app lock application. How to get current running task in lollipop? getRunningTaskinfo method is deprecated in lollipop API, then how to overcome this problem?
try this:
ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
we can get using UsageStats:
public static String getTopAppName(Context context) {
ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String strName = "";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
strName = getLollipopFGAppPackageName(context);
} else {
strName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
}
} catch (Exception e) {
e.printStackTrace();
}
return strName;
}
private static String getLollipopFGAppPackageName(Context ctx) {
try {
UsageStatsManager usageStatsManager = (UsageStatsManager) ctx.getSystemService("usagestats");
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
Log.i("LPU", "queryUsageStats size: " + queryUsageStats.size());
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (i == 0 && !"org.pervacio.pvadiag".equals(stats.getPackageName())) {
Log.i("LPU", "PackageName: " + stats.getPackageName() + " " + stats.getLastTimeStamp());
}
if (stats.getLastTimeStamp() > recentTime) {
recentTime = stats.getLastTimeStamp();
recentPkg = stats.getPackageName();
}
}
return recentPkg;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
// TO ENABLE USAGE_STATS
// Declare USAGE_STATS permisssion in manifest
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Best solution of get Running app in API 21 or up is below try it.
this work for me
private String retriveNewApp() {
if (VERSION.SDK_INT >= 21) {
String currentApp = null;
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
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<>();
for (UsageStats usageStats : applist) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
Log.e(TAG, "Current App in foreground is: " + currentApp);
return currentApp;
}
else {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String mm=(manager.getRunningTasks(1).get(0)).topActivity.getPackageName();
Log.e(TAG, "Current App in foreground is: " + mm);
return mm;
}
}
You can use the AccessibilityService to get current Running app.
Accessibility Service provides the onAccessibilityEvent event.
Following is some sample code.
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (event.getPackageName() != null && event.getClassName() != null) {
Log.d("Foreground App", event.getPackageName().toString());
}
}
}
You can find more info about Accessibility Service here
Are you sure? As I can see according to the latest Android docs, LOLLIPOP update doesnt allow you to know any info about other apps than your own!?
http://developer.android.com/reference/android/app/ActivityManager.html
You can see that all those methods are deprecated!
according to this ; the following code worked perfectly for me :
MOVE_TO_FOREGROUND and MOVE_TO_BACKGROUND added in sdk 21 and deprecated in sdk 29
ACTIVITY_RESUMED and ACTIVITY_PAUSED added in sdk 29
public static String getTopPkgName(Context context) {
String pkgName = null;
UsageStatsManager usageStatsManager = (UsageStatsManager) context
.getSystemService(Context.USAGE_STATS_SERVICE);
final long timeTnterval= 1000 * 600;
final long endTime = System.currentTimeMillis();
final long beginTime = endTime - timeTnterval;
final UsageEvents myUsageEvents = usageStatsManager .queryEvents(beginTime , endTime );
while (myUsageEvents .hasNextEvent()) {
UsageEvents.Event myEvent = new UsageEvents.Event();
myUsageEvents .getNextEvent(myEvent );
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
switch (myEvent .getEventType()) {
case UsageEvents.Event.ACTIVITY_RESUMED:
pkgName = myEvent .getPackageName();
break;
case UsageEvents.Event.ACTIVITY_PAUSED:
if (myEvent .getPackageName().equals(pkgName )) {
pkgName = null;
}
}
}else {
switch (event.getEventType()) {
case UsageEvents.Event.MOVE_TO_FOREGROUND:
pkgName = myEvent .getPackageName();
break;
case UsageEvents.Event.MOVE_TO_BACKGROUND:
if (myEvent .getPackageName().equals(pkgName )) {
pkgName = null;
}
}
}
}
return pkgName ;
}
Try this.. This worked for me.
ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)
{
String packageName = activityManager.getRunningAppProcesses().get(0).processName;
}
else if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
{
String packageName = ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();
}
else
{
String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
#Manish Godhani's answer (https://stackoverflow.com/a/38829083/8179249) works very well, but you have to give the right permissions for this !
See the two first points of that answer : https://stackoverflow.com/a/42560422/8179249
It works for me (before adding permissions I was getting 'null' too), as shown below :
Can be achieved like this.....
ActivityManager am =(ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo task = tasks.get(0); // current task
ComponentName rootActivity = task.baseActivity;
rootActivity.getPackageName();//*currently active applications package name*
For lollipop:
ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
if(Build.VERSION.SDK_INT > 20){
String activityName =mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
String activityName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
for complete example check this out...

check if there are 2 instances running

I am trying to check if my app is running already if the user is trying to enter it again.
it is possible if one app Launched anther one and the user entering with a mobile to the second one, and will be 2 instance.
my launcher app that starts the original one looks like that :
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("com.test.vayo");
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
On my original code I am trying to check if there is 2 instance but always get true on this code
if (processName == null) {
return false;
}
ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
for (RunningAppProcessInfo process : processes) {
if (processName.equals(process.processName)) {
return true;
}
}
return false;
the proccessName taken from this code, the pid is from android.os.Process.myPid():
private String getAppName(int pID)
{
String processName = "";
ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = context.getPackageManager();
while(i.hasNext())
{
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
try
{
if(info.pid == pID)
{
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
//Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ info.processName +" Label: "+c.toString());
//processName = c.toString();
processName = info.processName;
}
}
catch(Exception e)
{
//Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}
hope you can tell whats wrong why I am getting always true on my first block of code.
thanks a lot!!

Categories

Resources