How to run broadcast receiver for every one hour? - android

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);

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 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 get application name on various Android device?

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;
}

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...

Android mediaplayer volume change issues after phone call

I am using a service in my mp3 player to play media. I use mediaplayer object to play music. Normally the volume keys work when the music is playing. I also used Telephony Manager in my service to check phone calls. And I start and stop the music when the call is disconnected and is in progress respectively. But after the disconnection of phone call, the volume keys stopped working. I can see the dialog of volume change. But the sound volume don't change. Any idea? It is even happening in native player.
My player service:
public class PPlayService extends Service {
public static final int NOTIFICATION_NUMBER = 0;
Context conte;
MediaPlayer playHandler;
BroadcastReceiver broadcaster;
IncomingHandler mServiceHandler;
String online = "", link = "", name = "";
boolean playing = false;
boolean currentFlag = true;
Runnable runnable;
String[] uris, names;
int send;
SharedPreferences pre;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
AudioManager am;
// ........
PhoneStateListener phoneStateListener;
TelephonyManager mgr;
boolean notFromTelephone = false;
RemoteViews contentView;
BroadcastReceiver stopFromNoti, forwardFromNoti, backwardFromNoti;
Thread th;
public void handleMessage(Message msg) {
try {
playing = false;
if (playHandler != null) {
playHandler.setOnPreparedListener(null);
playHandler.setOnCompletionListener(null);
}
currentFlag = true;
System.gc();
if (online.equals("0")) {
contentView = new RemoteViews(getPackageName(),
R.layout.offline_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
PendingIntent backSong = PendingIntent.getBroadcast(conte, 0,
new Intent("backwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.backward_noti,
backSong);
PendingIntent frontSong = PendingIntent.getBroadcast(conte, 0,
new Intent("forwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.forward_noti,
frontSong);
} else {
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
}
Intent intt = new Intent(getBaseContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0,
intt, 0);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setContentIntent(pi).setAutoCancel(false);
notificationManager.notify(
Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.LOADING);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
if (playHandler != null) {
playing = false;
playHandler.reset();
} else {
playHandler = new MediaPlayer();
}
if (online.equals("1")) {
// Online Stream
playHandler.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
playHandler.setDataSource(link);
playHandler.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
if (playHandler != null) {
if (!playHandler.isPlaying()) {
playSongNow();
}
}
}
});
playHandler.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Offline Stream
playHandler = MediaPlayer.create(conte, Uri.parse(link));
playSongNow();
}
} catch (Exception e) {
}
}
#Override
public void onCreate() {
conte = this;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(new OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
}
}, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
forwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i >= send - 1) {
if (send > 0) {
name = names[0];
link = uris[0];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i + 1];
link = uris[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
backwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
stopFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime", playHandler.getDuration() / 1000);
conte.sendBroadcast(in);
playHandler.reset();
stopSelf();
}
stopSelf();
}
};
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
if (!notFromTelephone) {
notFromTelephone = false;
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
pre = getSharedPreferences("download", 0);
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0, new Intent(
"stopfromnoti"), PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, pit);
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setAutoCancel(false).setContentIntent(pit);
startForeground(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
broadcaster = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getExtras().getInt("action") == Mp3Constants.PAUSE) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
notFromTelephone = true;
playHandler.pause();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.PLAY) {
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.STOP) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
stopSelf();
} else if (arg1.getExtras().getInt("action") == Mp3Constants.SEEK) {
if (playHandler != null) {
{
playHandler.seekTo(arg1.getExtras()
.getInt("seekto") * 1000);
}
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.FORWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i >= send - 1) {
// if (send > 0) {
// name = names[0];
// link = uris[0];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i + 1];
// link = uris[i + 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
} else if (arg1.getExtras().getInt("action") == Mp3Constants.BACKWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
// for (int i = 0; i < send - 1; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// link = uris[i - 1];
// name = names[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler
// .obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// break;
// }
// }
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i == send || i == 0) {
// if (send > 0) {
// name = names[send - 1];
// link = uris[send - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i - 1];
// link = uris[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
}
}
};
registerReceiver(broadcaster, new IntentFilter(
"com.codebrew.bestmp3downloader.PPlayService"));
registerReceiver(stopFromNoti, new IntentFilter("stopfromnoti"));
registerReceiver(forwardFromNoti, new IntentFilter("forwardFromNoti"));
registerReceiver(backwardFromNoti, new IntentFilter("backwardFromNoti"));
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceHandler = new IncomingHandler(PPlayService.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
unregisterReceiver(broadcaster);
unregisterReceiver(stopFromNoti);
unregisterReceiver(forwardFromNoti);
unregisterReceiver(backwardFromNoti);
if (playHandler != null) {
if (playHandler.isPlaying()) {
playHandler.stop();
}
playHandler = null;
}
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
notificationManager.cancel(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER);
}
public void playSongNow() {
try {
playing = true;
playHandler.start();
runnable = new Runnable() {
public void run() {
while (playing) {
if (playing) {
try {
Intent in = new Intent(
Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.PLAYING);
if (playHandler.getCurrentPosition() / 1000 == playHandler
.getDuration() / 1000)
th.stop();
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
if (currentFlag) {
currentFlag = false;
contentView.setTextViewText(
R.id.name_of_the_song, name);
notificationManager
.notify(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.setContent(
contentView)
.build());
}
conte.sendBroadcast(in);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
th = new Thread(runnable);
th.start();
playHandler.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playing = false;
pre.edit().putBoolean("stopped", true).commit();
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
try {
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
} catch (Exception e) {
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
}
conte.sendBroadcast(in);
if (online.equals("0")) {
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
}
if (online.equals("1")) {
// stopSelf();
}
}
});
} catch (Exception e) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.FAILED);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
Toast.makeText(
getBaseContext(),
"Error playing: "
+ name
+ "\nFile broken or deleted! Please try another song",
Toast.LENGTH_SHORT).show();
stopSelf();
}
}
private void getSD() {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return;
}
Arrays.sort(files, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return +1;
} else if (((File) o1).lastModified() < ((File) o2)
.lastModified()) {
return -1;
} else {
return 0;
}
}
});
send = files.length;
uris = new String[send];
names = new String[send];
for (int i = 0; i < send; i++) {
File file = files[i];
// take the file name only
double size = file.length();
size = size / (1024 * 1024);
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
uris[send - 1 - i] = file.getPath();
names[send - 1 - i] = myfile;
}
}
static class IncomingHandler extends Handler {
private final WeakReference<PPlayService> mService;
IncomingHandler(PPlayService service) {
mService = new WeakReference<PPlayService>(service);
}
#Override
public void handleMessage(Message msg) {
PPlayService service = mService.get();
if (service != null) {
service.handleMessage(msg);
}
}
}
}

Categories

Resources