I'm developing an app that has a recurring task of sending call to the server and check whether the data is available for current date. I have implemented this successfully but I have an issue, when I kill the Process it's call the service again. I have monitored this through Logcat or it generate the PUSH notification too even the flag is not false (According to my logic). Why because I'm using *START_STICKY*?
I have used START_REDELIVER_INTENT flag too, it solved that issue but in the TaskManager of my cellphone my service status is on RESTART when I killed the process. Does the service is still running or it is in RESTART state?
I want my service run 24/7 without RESTART. either I kill the process like (weChat, Whatsapp, Viber) etc.
Can someone please sort out what I'm doing wrong? or give me the right direction. Help should be appreciated. Thanks
Service:
public int onStartCommand(Intent intent, int flags, final int startId) {
// Log.e("LocalService", "Received start id " + startId + ": " + intent);
Log.e("AlertService", "Alert-----Service Created");
// TODO Auto-generated method stub
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call service
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
currentDate = df.format(Calendar.getInstance().getTime());
String[] separated_currentDate = currentDate.split("-");
int actual_date = Integer.parseInt(separated_currentDate[0]);
Log.e("CurrentDate of my Device", currentDate);
Log.e("ad",""+actual_date);
if(flag == false)
{
Log.e("Flag-Status", "FALSE");
try {
savingDateinPref(currentDate);
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
Log.e("Flag-Status", "Calling Service");
new DoInBackground().execute(currentDate);
// currentDate = null;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defvalue");
String[] separated_val = val.split("-");
int pref_date = Integer.parseInt(separated_val[0]);
Log.e("pd", "" +pref_date);
if( (pref_date != actual_date) || ( pref_date < actual_date) || (pref_date > actual_date) )
{
flag = false;
Log.e("Flag-Status", "FALSE/bcoz date has been changed");
// String empty = null;
// savingDateinPref(empty);
}
}
}, 0, 5, TimeUnit.SECONDS);
return START_REDELIVER_INTENT;
}
Related
I have tried every suggestion I could find on the Internet to use Foreground Service to keep my app running beyond sleep and deep sleep modes but nothing has been successful so far.
I am working on a taxi booking application. I designed it to start emitting driver's location to server whenever the driver turns himself Online and stop emitting when Offline.
The following is the Foreground Service code that is started whenever driver turns himself Online and stopped when he presses online button which changes Common.CustomSocketOn to 0.
It work fine during screen wake and also works when the screen is off before the app gets killed.
However, even with WAKE_LOCK acquired, it still can't stay more than few minutes in sleep mode before getting killed by Android 7.
This failure to keep running in sleep mode breaks down many other features of the app because when the app gets killed silently, it does not get the chance to turn the driver Offline nor sign him out. As a result, the driver gets booking requests when his app is not running and therefore, cannot attend to it, and that keeps the booking from going to the next available driver. In fact, this causes so many other anomalies.
Please, can somebody tell me any other thing I need to do to keep Android from killing the Foreground Service.
public class OnlineForeGroundService extends Service {
private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
private static LocationListener locationListener;
private static LocationManager locationManager;
private PowerManager.WakeLock wakeLock;
public OnlineForeGroundService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG_FOREGROUND_SERVICE, "My foreground service.");
final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
try {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KEEP_AWAKE");
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null)
{
String action = intent.getAction();
if(action != null) {
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
Toast.makeText(getApplicationContext(), getText(R.string.going_online), Toast.LENGTH_SHORT).show();
wakeLock.acquire();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
//Toast.makeText(getApplicationContext(), getText(R.string.going_offline), Toast.LENGTH_SHORT).show();
break;
}
}
}
return super.onStartCommand(intent, flags, startId);
//return START_STICKY;
}
/* Used to build and start foreground service. */
#SuppressLint("MissingPermission")
private void startForegroundService()
{
if(OnlineForeGroundService.locationManager == null) {
OnlineForeGroundService.locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
if(OnlineForeGroundService.locationListener == null) {
OnlineForeGroundService.locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (Common.CustomSocketOn == 1) {
SharedPreferences userPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (Common.OldLatitude != 0 && Common.OldLongitude != 0) {
float distance[] = new float[1];
Location.distanceBetween(Common.OldLatitude, Common.OldLongitude, location.getLatitude(), location.getLongitude(), distance);
//Distance - 100
if (distance.length > 0 && distance[0] > 30) {
try {
JSONArray locAry = new JSONArray();
locAry.put(location.getLatitude());
locAry.put(location.getLongitude());
JSONObject emitobj = new JSONObject();
emitobj.put("coords", locAry);
emitobj.put("driver_name", userPref.getString("user_name", ""));
emitobj.put("driver_id", userPref.getString("id", ""));
emitobj.put("driver_status", "1"); //change by sir
emitobj.put("car_type", userPref.getString("car_type", ""));
emitobj.put("isdevice", "1");
emitobj.put("booking_status", userPref.getString("booking_status", ""));
emitobj.put("isLocationChange", 1);
if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0 && Common.socket != null && Common.socket.connected()) {
Common.socket.emit("Create Driver Data", emitobj);
} else if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0 && Common.socket == null) {
Common.socket = null;
SocketSingleObject.instance = null;
Common.socket = SocketSingleObject.get(getApplicationContext()).getSocket();
Common.socket.connect();
Common.socket.emit("Create Driver Data", emitobj);
} else if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0 && Common.socket != null && !Common.socket.connected()) {
Common.socket.connect();
Common.socket.emit("Create Driver Data", emitobj);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Common.OldLatitude = location.getLatitude();
Common.OldLongitude = location.getLongitude();
}
}
if (Common.OldLatitude == 0 && Common.OldLongitude == 0) {
Common.OldLatitude = location.getLatitude();
Common.OldLongitude = location.getLongitude();
}
}
else{
stopForegroundService();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude", "enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
}
if(Common.isPermission){
if(Common.CustomSocketOn == 1){
try {
OnlineForeGroundService.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Common.DriverDistanceTime, Common.DriverDistance, OnlineForeGroundService.locationListener);
OnlineForeGroundService.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, Common.DriverDistanceTime, Common.DriverDistance, OnlineForeGroundService.locationListener);
}
catch (Exception e){
e.printStackTrace();
}
}
}
Log.d(TAG_FOREGROUND_SERVICE, "Starting foreground service.");
String onlineSticker = getText(R.string.app_name)+" - Online";
Intent notificationIntent = new Intent(this, HomeActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification;
/*if(android.os.Build.VERSION.SDK_INT >= 26) {
notification = new Notification.Builder(HomeActivity.class, NotificationManager.IMPORTANCE_HIGH)
.setContentTitle(getText(R.string.app_name))
.setContentText(getText(R.string.you_are_online))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker(onlineSticker)
.build();
//startForeground(ONGOING_NOTIFICATION_ID, notification);
// Start foreground service.
}
else{*/
notification = new Notification.Builder(this)
.setContentTitle(getText(R.string.app_name))
.setContentText(getText(R.string.you_are_online))
.setPriority(Notification.PRIORITY_HIGH)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker(onlineSticker)
.build();
//}
startForeground(397, notification);
}
private void stopForegroundService()
{
Toast.makeText(getApplicationContext(), getText(R.string.going_offline), Toast.LENGTH_SHORT).show();
if(Common.isPermission){
if(Common.CustomSocketOn == 0){
try {
OnlineForeGroundService.locationManager.removeUpdates(OnlineForeGroundService.locationListener);
//OnlineForeGroundService.locationListener = null;
}
catch (Exception e){
e.printStackTrace();
}
}
}
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
if (null != wakeLock && wakeLock.isHeld()) {
wakeLock.release();
}
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
}
Here is the androidManifest entry for the service and WAKE_LOCK permission:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service
android:name=".driver.service.OnlineForeGroundService"
android:process=".process"
android:enabled="true"
android:exported="true" ></service>
Please see this excellent site which provides a vast amount of information covering various different handset vendors and Android API versions.
This has helped me massively understand the very common Android developer problem of dealing with reports and feedback of foreground services being killed despite following the documented steps to ensure your service is setup correctly to avoid being shutdown.
https://dontkillmyapp.com/stock_android
The site includes mention of the Dianne Hackborn comments which are now no longer accessible on the Google plus (due to it's end of life).
Ultimately it seems that the solution to prevent your Foreground Service from being shutdown may vary across Android OS version and device manufacturer, but this site provides a good summary of the steps users can be directed to follow and also developers can implement (where possible) to try and mitigate this issue.
Check how you are starting your OnlineForeGroundService.
On Android Oreo and above it needs to be started with startForegroundService(Intent intent), not startService(Intent intent)
For example something like:
final Intent serviceIntent = new Intent(context, OnlineForeGroundService.class);
serviceIntent.setAction(OnlineForeGroundService.ACTION_START_FOREGROUND_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
} else {
startService(serviceIntent);
}
These methods are implemented in a class extending Service. A new service is started every time a button is pressed.
If the button is pressed once, LogCat outputs what I expect, which includes a final output of "Service onDestroy." However, when the button is pressed twice, the second time before the first service ended, "Service onDestroy." displays only once when the first service is done, and the second service prints out the rest of "Service Running" logs but not "Service onDestroy."
Can anyone tell me why? Thank you!
public int onStartCommand(Intent intent,int flags, int startId) {
Log.i(TAG,"Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
long endTime = System.currentTimeMillis() + 10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized(this) {
try {
wait(endTime - System.currentTimeMillis());
}catch (Exception e) {
}
}
}
Log.i(TAG,"Service running");
}
stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG,"Service onBind");
return null;
}
#Override
public void onDestroy() {
Log.i(TAG,"Service onDestroy");
}
In the guide for Services they use don't use stopSelf() but stopSelf(startId) when extending Service. The first stopSelf() propably stops both executions of your Service.
See here: http://developer.android.com/guide/components/services.html
Edit: Also a service is only created and destroyed once even when there are several executions of it running it is still a single service. In your case (a Bound Service) it will only be destroyed when the last excecution finishes. For logging every excecution ending you could try to override the stopSelf(int startId) method.
how can i prevent this service with thread to dont be killed from android, i need this notifications always runnig, but when is mobile locked, nothing will happen. I think android kill service or thread or something like that
MainActivity in onCreate
startService(new Intent(this, NotifyService.class));
My service
public class NotifyService extends Service {
private DatabaseOp mDbHelper;
public Vibrator vibrator;
String username;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate ()
{
mDbHelper = new DatabaseOp(this);
final boolean cyklus = true;
Thread vlakno = new Thread (new Runnable()
{
#Override
public void run()
{
while (cyklus)
{
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String sysDate = getSysDate();
String sysDate2 = getSysDate2();
String time = getSysTime();
mDbHelper.open();
Log.v( "sysDate", sysDate );
Cursor cursorU = mDbHelper.fetchUlohaS(0, sysDate);
if (cursorU.getCount() > 0)
{
String idU = cursorU.getString(cursorU.getColumnIndexOrThrow(DatabaseOp.KEY_ID));
String dbDateU = cursorU.getString(cursorU.getColumnIndexOrThrow(DatabaseOp.KEY_DATE));
String menoU = cursorU.getString(cursorU.getColumnIndexOrThrow(DatabaseOp.KEY_NAZOV));
String mHodina = getResources().getString(R.string.cas)+" "+cursorU.getString(cursorU.getColumnIndexOrThrow(DatabaseOp.KEY_HODINA));
Log.v( "task", dbDateU+"/"+sysDate );
if (dbDateU.equals(sysDate))
{
Notify(menoU, mHodina, idU, 0);
}
}
Cursor cursorS = mDbHelper.fetchSviatokS(3, sysDate2);
if (cursorS.getCount() > 0)
{
String idS = cursorS.getString(cursorS.getColumnIndexOrThrow(DatabaseOp.KEY_ID));
String dbDateS = cursorS.getString(cursorS.getColumnIndexOrThrow(DatabaseOp.KEY_DATUM));
String menoS = cursorS.getString(cursorS.getColumnIndexOrThrow(DatabaseOp.KEY_NAZOV));
if (dbDateS.equals(sysDate2) && time.equals("09:00"))
{
Notify(menoS,getResources().getString(R.string.title_section4), idS, 3);
}
}
mDbHelper.close();
}
}
});
vlakno.start();
}
}
Have you tried to use ForgroundService?
Checkout this repo for an example - https://github.com/supercurio/foreground-service-sample-app
I think you should consider AlarmManager. See http://developer.android.com/reference/android/app/AlarmManager.html.
To tip the system to keep your Service alive as long as possible (i.e. before RAM is very short or user kills the service by hand through application info screen), you need to run it as a foreground service -- by using startForeground() method.
If you're looking for a way to run when the device is turned off, read the Keeping The Device Awake training page and consider using AlarmManager instead as suggested by #khris if your task is not very critical in terms of timing precision.
I am trying to create a service with background task. 24 hrs once the thread would start and do the process.
I have tried like this. but its not worked.
public class MyService extends Service {
int counter = 0;
static final int UPDATE_INTERVAL = 10 * 1000; // / 1000 = 1 second
private Timer timer = new Timer();
Home home;
private boolean isRunning = true;
#Override
public IBinder onBind(Intent intent) {
// Not implemented...this sample is only for starting and stopping
// services.
// Service binding will be covered in another tutorial
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Announcement about starting
Toast.makeText(this, "Starting the Demo Service", Toast.LENGTH_SHORT)
.show();
// Start a Background thread
isRunning = true;
// Thread backgroundThread = new Thread(new BackgroundThread());
BackgroundThread();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Background thread
isRunning = false;
// Announcement about stopping
Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT)
.show();
}
private void BackgroundThread() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
String month = String.valueOf(c.get(Calendar.MONTH) + 1);
String year = String.valueOf(c.get(Calendar.YEAR));
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String months = null;
if (month.startsWith("0") || month.startsWith("1")) {
months = year + "-" + month + "-" + day;
home.loadCalender(months);
} else {
months = year + "-" + "0" + month + "-" + day;
home.loadCalender(months);
}
}
}, 0, UPDATE_INTERVAL);
/*
* counter = 0; while(isRunning) { System.out.println(""+counter++);
* //Thread.currentThread().sleep(5000);
*
* }
*/
System.out.println("Background Thread is finished.........");
}
}
In my main activity, i have started the Service...
plz help me to do this task.
Use AlarmManager to schedule your alarm to occur once per day, using setRepeating() (or perhaps setInexactRepeating(). Please do not waste the user's RAM trying to have a service running all of the time watching the clock tick.
Normally, when I close my app I send an intent to my service to signal to safely shutdown using onStartCommand with an extra boolean of true. I do this in my application class' onTerminate. I added the if statements because I was getting a nullptrexception when force closing the app in this block.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
boolean state = intent.getBooleanExtra("terminate", false);
mSafeShutdown = state;
}
else if (mUpdater != null && mUpdater.isRunning()) {
Log.d(TAG, "activity force closed?" +
" Attempting to handle service thread shutdown safely...");
mUpdater.isRunning(false);
try {
mUpdater.join();
} catch (InterruptedException e) {
Log.e(TAG,"Service's UpdaterThread couldn't join");
}
}
return START_STICKY;
}
however, this causes my service to stay alive -
static final int DELAY = 2000;
public void run() {
while (mIsRunning) {
if (!mJobQueue.isEmpty()) {
//do work
}
else if (mSafeShutdown) {
mIsRunning = false;
stopSelf();
}
else {
sleep(DELAY);
}
}
}
The fact that force closing disconnects the debugger its making hard to see exactly whats going on.. Is there a better/safer way to tell my service thread that the application has shut down?
since your thread is a child class, create a method in it to shut it down the thread and call it in your parent class.
An example can be found here
http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html