I'm trying to fetch application's name when it hits foreground. I've accomplished this by running a background service in which I've implemented Runnable for running this service every second. This is working fine in all OS except in Jelly Bean. My service gets killed. I know that if an app consumes more RAM then it kills available background services to manage the required space. For example high resolution games. But I'll be loosing data. I implemented Foreground Services. Its working fine. My doubt is, does this effect any way in the matter efficiency or battery consumption?? Is there any other method other than foreground??
This is the service which I have made foreground.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ReceiverRunning = true;
context = this;
Intent intent1 = new Intent(this, ComponentSelector.class);
PendingIntent pendingIndent = PendingIntent.getActivity(this, 1, intent1, 0);
Notification mNotification = new Notification(R.drawable.ic_launcher, "BackgroundApp", System.currentTimeMillis());
mNotification.setLatestEventInfo(this, "BatteryUSage", "Click to open to app", pendingIndent);
mNotification.flags = mNotification.flags|Notification.FLAG_ONGOING_EVENT;
startForeground(1000, mNotification);
// Start service if not started.
if (!ForegroundApp.isRunning == true) {
context.startService(new Intent(context, Brightness.class));
}
boolean has_tele = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TELEPHONY);
if (has_tele == true) {
TelephonyManager teleman = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
if (teleman != null)
deviceId = teleman.getDeviceId();
}
uId = deviceInfo();
try {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info != null) {
Log.d("wifiRun", "Network available");
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo.State wifi = null;
if (conMan.getNetworkInfo(1).isAvailable())
wifi = conMan.getNetworkInfo(1).getState();
if (wifi == NetworkInfo.State.CONNECTED
|| wifi == NetworkInfo.State.CONNECTING) {
wifiCheck = true;
context.startService(new Intent(context, WiFi.class));
Log.d("wifiRun","wifiCheck: " +wifiCheck);
} else {
Log.d("wifiRun","wifiCheck: " +wifiCheck);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// Register for Screen On and Screen Off.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
sReceiver = new ServiceDefinition();
registerReceiver(sReceiver, intentFilter);
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}