I am trying to spawn a service that stays alive all the time, even if the user closes the application. According to these threads
Keep location service alive when the app is closed
Android Service Stops When App Is Closed
Android: keep Service running when app is killed
this can be accomplished with IntentServices or Service.START_STICKY
Yet, I tried both types of services without success. In other words, my services get killed when the app is closed by the user. Can someone point out if this is can be done and how? Here is what I have tried without success:
With IntentService:
public class MyIntentService extends IntentService {
private final int mPollingTimeMS = 500;
private int mInitializationPollingCount = 0;
private Thread mPollThread;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
mPollThread = new Thread() {
public void run() {
while (true) {
try {
Log.e(Constants.Engine.LOGGER_TAG_DEV,
"SDK Service Running: " +
mInitializationPollingCount * mPollingTimeMS +
"ms have elapsed");
mInitializationPollingCount++;
sleep(mPollingTimeMS);
} catch (Exception e) {
StackTraceElement trace = new Exception().getStackTrace()[0];
Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" +
trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber());
}
}
}
};
mPollThread.start();
}
}
and with Services:
public class MyService extends Service {
public MyService() {
}
private final int mPollingTimeMS = 500;
private int mInitializationPollingCount = 0;
private Thread mPollThread;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPollThread = new Thread() {
public void run() {
while (true) {
try {
Log.e(Constants.Engine.LOGGER_TAG_DEV,
"SDK Service Running: " +
mInitializationPollingCount * mPollingTimeMS +
"ms have elapsed");
mInitializationPollingCount++;
sleep(mPollingTimeMS);
} catch (Exception e) {
StackTraceElement trace = new Exception().getStackTrace()[0];
Logger.e(Constants.Engine.LOGGER_TAG_APP, "[Exception:" + e.toString() + "]" +
trace.getClassName() + "->" + trace.getMethodName() + ":" + trace.getLineNumber());
}
}
}
};
mPollThread.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// I tried to return null here, but this
// service gets killed no matter what.
return null;
}
}
and here is the manifest:
<service
android:name=".mycompany.MyService"
android:enabled="true"
android:exported="true"
android:process=":process1">
</service>
<service
android:name=".mycompany.MyIntentService"
android:process=":process2"
android:exported="false">
</service>
I shall added that I am closing the test app not with a close button, but using the Android OS app manager. See picture below
Lastly, the driver activity (not much there)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent1 = new Intent(getBaseContext(), MyService.class);
startService(intent1);
Intent intent2 = new Intent(getBaseContext(), MyIntentService.class);
startService(intent2);
}
}
I also try to add a notification and make it a foreground service but still the same thing. The moment I close the app, everything gets killed. This is what I added:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
...etc..
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
int iconId = R.mipmap.ic_launcher;
int uniqueCode = new Random().nextInt(Integer.MAX_VALUE);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(iconId)
.setContentText("Context Text")
.setContentIntent(pendingIntent).build();
startForeground(uniqueCode, notification);
}
Here is an example of foreground service that I use and that works, it remains active when the app is closed. Of course, it also must be started, and for that task the app must be running at a first glance, or a receiver of a boot event must be set, but this is another story.
public class MyService extends Service {
static final int NOTIFICATION_ID = 543;
public static boolean isServiceRunning = false;
#Override
public void onCreate() {
super.onCreate();
startServiceWithNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
startServiceWithNotification();
}
else stopMyService();
return START_STICKY;
}
// In case the service is deleted or crashes some how
#Override
public void onDestroy() {
isServiceRunning = false;
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Used only in case of bound services.
return null;
}
void startServiceWithNotification() {
if (isServiceRunning) return;
isServiceRunning = true;
Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
notificationIntent.setAction(C.ACTION_MAIN); // A string containing the action name
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.my_string))
.setSmallIcon(R.drawable.my_icon)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(contentPendingIntent)
.setOngoing(true)
// .setDeleteIntent(contentPendingIntent) // if needed
.build();
notification.flags = notification.flags | Notification.FLAG_NO_CLEAR; // NO_CLEAR makes the notification stay when the user performs a "delete all" command
startForeground(NOTIFICATION_ID, notification);
}
void stopMyService() {
stopForeground(true);
stopSelf();
isServiceRunning = false;
}
}
Then I run it with
Intent startIntent = new Intent(getApplicationContext(), MyService.class);
startIntent.setAction(C.ACTION_START_SERVICE);
startService(startIntent);
Please note the two constants used as Actions, these are Strings that must start with the package name.
IntentService
Using IntentService is probably not the best approach. By default IntentService stops itself after onHandleIntent(Intent) returns and there's no work left to do (i.e. the request queue is empty). This is explained in the official docs of IntentService:
When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
In your case, onHandleIntent(Intent) creates a thread but returns right away, which makes it stop by itself.
Service + startForeground()
Using a regular Service in foreground mode should work as long as you keep that service running on a separate process. For that, you need:
Make the onStartCommand() return START_STICKY.
Call the method to show the notification right in onCreate().
Run the service in a separate process (using android:process=":something").
Based on the post, it seems that you've tried some of these steps in isolation but never tried all of them at the same time.
If none of the answers above are working, maybe it is a manufacturer specific issue. Some MI phones, for instance, kill the foreground service when the user kill the app via task manager.
I recommend you to test the app on a virtual device, so you can check if it is or isn't this kind of issue.
Hope it helps!
You can simply call your service in your onStop() method inside your activity.
Even when user stops the app the service will still be running.
Try the answers for this similar question: Bad notification for startForeground in Android app
Related
I am developing an app where the app will detect Bluetooth signals (Sensoro Smart Beacon device) and open the activity. But I want the app to still be able to detect the signal even when the application on the background or even when killed. I used a foreground service, it detects the signal when I open the application and move between activities but when sending the app to the background and opening other applications, the listener stops although the service still working. I am printing the logs. System.out.println("Sensoro 2" ); keeps printing even when I kill the application or open another application. But the printing logs in BeaconManagerListener are not working. I tried to use background service but it didn't work also.
Can you please advise if there is a way to make the listener works in a service when the app in background or killed?
Here is the service code:
public class MyService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
int service_timer=0;
Timer timer = new Timer();
SensoroManager sensoroManager;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sensoroManager = SensoroManager.getInstance(MyService.this);
String input = intent.getStringExtra("inputExtra");
System.out.println("Sensoro 2" );
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
//do heavy work on a background thread
//stopSelf();
if (sensoroManager.isBluetoothEnabled()) {
sensoroManager.setCloudServiceEnable(true);
/**
* Enable SDK service
**/
try {
sensoroManager.startService();
} catch (Exception e) {
e.printStackTrace(); // Fetch abnormal info
}
}
else
{
Toast.makeText(MyService.this,"Bluetooth off",Toast.LENGTH_LONG).show();
}
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//your method
System.out.println("Sensoro 2" );
BeaconManagerListener beaconManagerListener = new BeaconManagerListener() {
#Override
public void onUpdateBeacon(ArrayList<Beacon> beacons) {
// Refresh sensor info
for (Beacon beacon : beacons
) {
System.out.println("Sensoro 3" );
// System.out.println("Sensoro" +beacon.getAccuracy());
}
}
#Override
public void onNewBeacon(Beacon beacon) {
if (beacon.getSerialNumber().equals("0117C59B243C")){
System.out.println("Sensoro 3" );
System.out.println("Sensoro acc" +beacon.getAccuracy());
}
}
#Override
public void onGoneBeacon(Beacon beacon) {
if (beacon.getSerialNumber().equals("0117C59B243C")){
System.out.println("Sensoro acc gone");
System.out.println("Sensoro acc Timer" +service_timer);
}
}
};
sensoroManager.setBeaconManagerListener(beaconManagerListener);
}
}, 0, 2000);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// timer.cancel();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Here is where I call it:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService();
}
public void startService() {
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
System.out.println("Sensoro 1 ");
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService() {
Intent serviceIntent = new Intent(this, MyService2.class);
stopService(serviceIntent);
}
public void movingg(View view) {
Intent intent=new Intent(this,Usermain.class);
startActivity(intent); }
}
This is not 100% a match with what are you searching but this is near to what are you want.
You can use WorkManager that is working even application in the background. There are two types of WorkManager. 1) OneTimeWorkRequest 2) PeriodicWorkRequest.
So you can you PeriodicWorkRequest which will call every 15 min(minimum interval) and you can add your code in WorkManager to detect Bluetooth signals. So you can able to detect Bluetooth single at every 15 mins of intervals.
I hope this will help you solve your problem.
I don't know if this will help you, but here's my answer:
public void startService() {
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
System.out.println("Sensoro 1 ");
startService(serviceIntent);
}
I looked at the Android rules and regulations page
According to Google documents, from Android 8 onwards, all applications that do not have a Google-approved signature will be removed from the background after a few minutes.
But the solutions:
The first solution is to run the application in debug mode
The second solution is to assign a signature to the application and send it to Google for approval
recommend:
The third solution is to remove the google play service application from the emulator or android phone
you can use BroadcastReceiver.
if your app is killed or in the background ,the broadcast receiver is catch the event of bluetoth
I see there are two issues with your approach here.
First you should your check for specific beacon serial number could be causing issue.
Secondly you are using a Timer that goes off every 2 seconds and every time it does it adds a new BeaconManagerListener which should not be the case you should extract the listener outside maybe make it a class member and then use the same listener every time instead of continuously creating new listener which then replaces the old one.
Also why add listener after 2 seconds I think is should be added before calling sensoroManager.startService()
Lastly if the task is not needed to be repeated every few seconds and can be done with an interval >= 15 mins then consider using Periodic Work Manager instead.
I am facing a trouble here where i want a foreground service should run untill its task get completed and once task get completed foreground service should stop. But the problem here is even if its Foreground Service the Service is getting killed when user close the app only in Nougat Version. I have checked Marshamallow,Oreo, Android pie version the scenario is working fine. But In Nougat and MI phone this scenario is not working correctly.
Below is Service code which i am running as a demo
public class MyForeGroundService 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";
public static final String PRIMARY_CHANNEL = "default";
public MyForeGroundService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG_FOREGROUND_SERVICE, "My foreground service onCreate().");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null)
{
String action = intent.getAction();
switch (action)
{
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
Toast.makeText(getApplicationContext(), "Foreground service is started.", Toast.LENGTH_LONG).show();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
Toast.makeText(getApplicationContext(), "Foreground service is stopped.", Toast.LENGTH_LONG).show();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
/* Used to build and start foreground service. */
private void startForegroundService()
{
NotificationCompat.Builder mBuilder = notificationBuilder();
// Start foreground service.
startForeground(1, mBuilder.build());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setAction("SERVICE_CONNECTED");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
},10000);
}
private void stopForegroundService()
{
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
public NotificationCompat.Builder notificationBuilder(){
NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this, PRIMARY_CHANNEL)
.setContentTitle("Dummy Title")
.setContentText("Dummy Message")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Big text Message"
))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(R.drawable.app_icon_white);
mBuilder.setColor(getResources().getColor(R.color.theme_color));
} else {
mBuilder.setSmallIcon(R.drawable.app_icon_white);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getResources().getString(R.string.feroz_channel_name);
String description = getResources().getString(R.string.feroz_channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, name, importance);
channel.enableLights(true);
channel.setLightColor(getResources().getColor(R.color.theme_color));
channel.enableVibration(true);
channel.setDescription(description);
NotificationManager notificationManager1 = getSystemService(NotificationManager.class);
notificationManager1.createNotificationChannel(channel);
}
Intent stopIntent = new Intent(this, MyForeGroundService.class);
stopIntent.setAction(ACTION_STOP_FOREGROUND_SERVICE);
PendingIntent stopPlayIntent = PendingIntent.getService(this, 0, stopIntent, 0);
mBuilder.addAction(R.drawable.ic_launcher_new,"STOP",stopPlayIntent);
Intent intent = new Intent(this, CreateForegroundServiceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setUsesChronometer(true);
return mBuilder;
}
}
Below is code which start the service from activity
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CreateForegroundServiceActivity.this, MyForeGroundService.class);
intent.setAction(MyForeGroundService.ACTION_START_FOREGROUND_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
});
Button stopServiceButton = (Button)findViewById(R.id.stop_foreground_service_button);
stopServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CreateForegroundServiceActivity.this, MyForeGroundService.class);
intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
});
I think startForeGroundService works well but startService is not working as expected. The behaviour is so confusing, When i kill the app foreground service gets restarted , but if i open the app and press a button to stop the service i can see intent sent to the Service. But still the service is running.
PS: I want a service which run for like 10 Mins irrespective of App is in Background or not. It shouldn't get Restarted at any cost. For e.g if i am playing a music from background its should play till end. it should stop as soon as music ended. I dont want it to be restart
Below is logs when i start the service on button click and killed the app :
2019-02-15 13:35:56.091 11120-11120/sample.androido.com.myapplication D/MyForeGroundService: My foreground service onCreate().
2019-02-15 13:36:01.956 1459-3975/? W/ActivityManager: Scheduling restart of crashed service sample.androido.com.myapplication/.services.MyForeGroundService in 1000ms
2019-02-15 13:36:02.975 1459-1509/? I/ActivityManager: Start proc 11170:sample.androido.com.myapplication/u0a154 for service sample.androido.com.myapplication/.services.MyForeGroundService
2019-02-15 13:36:03.674 11170-11170/? D/MyForeGroundService: My foreground service onCreate().
From the official Android documentation for startForegroundService() method.
Note that calling this method does not put the service in the started state itself, even though the name sounds like it. You must always call ContextWrapper.startService(Intent) first to tell the system it should keep the service running, and then use this method to tell it to keep it running harder.
According to the above statement, you should call startService() first and then startForegroundService()
If I start a service with startService in a Activity I get:
1 processes and 1 service
If I now swipe that Activity away. I.e remove it, I get:
0 processes and 1 service
Why is this? And what is a Process and what is a Service in the Android world?
I use START_STICKY and if I stop the service via Settings, Apps and Running, it is not started again, why?
Update1 some code:
Activity:
startService(new Intent(getApplicationContext(), MyService.class));
Service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Starting service");
return(START_STICKY);
}
what is the definition of process in android world? same as defined at any operating system - your application is "alive" from the system's point of view, it has active memory allocation stack, and may run or not Activities, Services and so on...
I think that you struggling your had "how can it be that running process = 0" but services = 1 not making scenes, and you are right.
the running applications display shown from the settings app is not made only for developers, but also for users, I guess that's why most vendors decided to show active tasks as process. basically, in this display - running process = running task.
most application starts only one task (the main activity with the launcher flag starts automatically in that mode). there will be more tasks only if other activities would start explicitly with that flag.
so, if your app have 2 activities that started at new task mode - you'll see "2 process".
if your app not running at all (your process really not alive) - then you won't see the app in the running apps screen.
Turned out to be a bug in KitKat.
(Sometimes I think getting anything done in Android is a big hassle!)
Android Services: START_STICKY does not work on Kitkat
https://code.google.com/p/android/issues/detail?id=63793
Fix in Service:
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(), this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
}
The Main problem in your case is ur unable to start the service when app closed,that time android OS will kill the service, If you are not able to restart the service then call a alam manger to start the reciver like this,
Manifest is,
<service
android:name=".BackgroundService"
android:description="#string/app_name"
android:enabled="true"
android:label="Notification" />
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="REFRESH_THIS" />
</intent-filter>
</receiver>
IN Main Activty start alarm manger in this way,
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager) getSystemService(alarm);
Intent intent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 123456789, intent, 0);
int type = AlarmManager.RTC_WAKEUP;
long interval = 1000 * 50;
am.setInexactRepeating(type, System.currentTimeMillis(), interval, pi);
this will call reciver and reciver is,
public class AlarmReceiver extends BroadcastReceiver {
Context context;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
System.out.println("Alarma Reciver Called");
if (isMyServiceRunning(this.context, BackgroundService.class)) {
System.out.println("alredy running no need to start again");
} else {
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
}
public static boolean isMyServiceRunning(Context context, Class<?> serviceClass) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
if (services != null) {
for (int i = 0; i < services.size(); i++) {
if ((serviceClass.getName()).equals(services.get(i).service.getClassName()) && services.get(i).pid != 0) {
return true;
}
}
}
return false;
}
}
And this Alaram reciver calls once when android app is opened and when app is closed.SO the service is like this,
public class BackgroundService extends Service {
private String LOG_TAG = null;
#Override
public void onCreate() {
super.onCreate();
LOG_TAG = "app_name";
Log.i(LOG_TAG, "service created");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "In onStartCommand");
//ur actual code
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// Wont be called as service is not bound
Log.i(LOG_TAG, "In onBind");
return null;
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroyed");
}
}
I want to open a screen when a particular event occurs, regardless of the screen where I am now, how do I do that?
Intent Iatualizar = new Intent(this, Atualizar.class);
startActivity(Iatualizar);
The above code works if I'm with the screen open the program, but not work when the screen was in the background. How to make it work? thank you
Add FLAG_ACTIVITY_NEW_TASK to your Intent. If you check the log cat, it will also tell you this.
You should just create a service that loads your activity when the event happens.
To do this, you can start the service when your application is loaded, and have your event receiver in your service class. This way, even if other applications are running and your application is not in the foreground (showing on the screen) you will still be able to trigger off the event.
Android garbage collection will try to kill off your activity if it isn't in the foreground and you start running low on resources.
If you want to go a step further and make the service a foreground service, then it will theoretically be the last thing that Android will kill when it is running low on memory. Let me know if you need a code example.
Hopefully this helps you!
Cheers
-- EDIT --
Here is a code example to get you started.
In your activities onCreate call some code similar to what you have above to launch your service.
ie:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent IatualizarService = new Intent(this, AtualizarService.class);
startService(Iatualizar);
}
You could also have this in your onResume if you want, (or start it from a button, or however you want this service to start).
Then create a service class like so:
public class AtualizarService extends Service {
private final IBinder mBinder = new MyBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
// In here you can make your service a foreground service to help prevent garbage collection from occurring.
makeforeground();
}
private boolean makeforeground() {
String msg = "Turning on foreground service";
ErrorLog.i(getApplicationContext(), TAG, msg);
try {
Notification notification = new Notification(
R.drawable.ic_dialog_info,
getText(R.string.notification_text),
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent activityIntent = new Intent(this, YourMainActivity.class);
activityIntent.setAction(Intent.ACTION_MAIN);
activityIntent.addCategory(Intent.CATEGORY_LAUNCHER);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
activityIntent, 0);
notification.setLatestEventInfo(this,
getText(R.string.notification_title),
getText(R.string.notification_text), pendingIntent);
startForeground(1234567890, notification); // random id
return true;
} catch (Exception e) {
String error = "displayNotification Error Message: "
+ e.getMessage() + " Cause: " + e.getCause();
ErrorLog.e(GlobalParameters.getContext(),
TAG + " Notification Foreground Service", error);
return false;
}
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
AtualizarService getService() {
return AtualizarService .this;
}
}
}
Then inside this service class, you can add in a broadcast receiver that can trigger on any event you want. And then load up your activity if you want it to.
Cheers
Try this, you can also start a service using the code below
Intent Iatualizar = new Intent(this, Atualizar.class);
Iatualizar.addFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(Iatualizar);
I am using Service in my application and it needs to run until my application is uninstalled, but the problem is it gets killed by OS.
How can we prevent it from being killed by OS? Or if it gets killed can we restart that service again through programmatically?
You may run the service in the foreground using startForeground().
A foreground service is a service that's considered to be something
the user is actively aware of and thus not a candidate for the system
to kill when low on memory.
But bear in mind that a foreground service must provide a notification for the status bar (read here), and that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
Note: This still does not absolutely guarantee that the service won't be killed under extremely low memory conditions. It only makes it less likely to be killed.
I've been puzzled by the same issue to yours recently.but now,I've found a good solution.
First of all,you should know that, even your service was killed by OS, the onCreate method of your service would be invoked by OS in a short while.So you can do someting with the onCreate method like this:
#Override
public void onCreate() {
Log.d(LOGTAG, "NotificationService.onCreate()...");
//start this service from another class
ServiceManager.startService();
}
#Override
public void onStart(Intent intent, int startId) {
Log.d(LOGTAG, "onStart()...");
//some code of your service starting,such as establish a connection,create a TimerTask or something else
}
the content of "ServiceManager.startService()" is:
public static void startService() {
Log.i(LOGTAG, "ServiceManager.startSerivce()...");
Intent intent = new Intent(NotificationService.class.getName());
context.startService(intent);
}
However, this solution is just available for the situation of your service being killed by GC.Sometimes our service might be killed by user with Programme Manager.In this situation,your prosses will be killed,and your service will never been re-instantiated.So your service can not be restarted.
But the good news is,when the PM kill your service,it will call your onDestroy method.So we can do something with that method.
#Override
public void onDestroy() {
Intent in = new Intent();
in.setAction("YouWillNeverKillMe");
sendBroadcast(in);
Log.d(LOGTAG, "onDestroy()...");
}
The string of "YouWillNeverKillMe" is a custom action.
The most important thing of this method is,don't add any code before send the broadcast.As system will not wait for completion of onDestroy(),you must send out the broadcast as soon as posible.
Then regist a receiver in manifast.xml:
<receiver android:name=".app.ServiceDestroyReceiver" >
<intent-filter>
<action android:name="YouWillNeverKillMe" >
</action>
</intent-filter>
</receiver>
Finally,create a BroadcastReceiver,and start your service in the onReceive method:
#Override
public void onReceive(Context context, Intent intent) {
Log.d(LOGTAG, "ServeiceDestroy onReceive...");
Log.d(LOGTAG, "action:" + intent.getAction());
Log.d(LOGTAG, "ServeiceDestroy auto start service...");
ServiceManager.startService();
}
Hope this will be helpful to you,and excuse my poor written english.
Override method onStartCommand() in your service class and simply return START_STICKY (as suggested by "Its not blank"). That's all you need. If the process that runs your service gets killed (by a low memory condition for example), the Android system will restart it automatically (usually with some delay, like 5 seconds).
Don't use onStart() anymore as suggested in another answer, it's deprecated.
use
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//**Your code **
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
ref Documentation lifecycle of Service.
Edit added method.
As far i know, onDestroy() will be called only when the service is explicitly stopped(Force Stop). But this method won't get called in case the service gets killed by OS/swiping the Recent Apps list. In those cases another event handler named onTaskRemoved(Intent) gets called. This is due to a defect in Android 4.3-4.4 as per the link here. Try using the below code:-
public void onTaskRemoved(Intent intent){
super.onTaskRemoved(intent);
Intent intent=new Intent(this,this.getClass());
startService(intent);
}
I found another solution of the problem which gurantees that your service will be always alive. In my case, this scheme resloves also the problem with FileObserver, which stops work after some period of time.
Use an activity (StartServicesActivity) to start the service (FileObserverService) as Foreground service.
Use BroadcastReceiver class (in example CommonReceiver) to restart your service in some special situations and in case it was killed.
I used this code in my app "Email Pictures Automatically"
https://play.google.com/store/apps/details?id=com.alexpap.EmailPicturesFree
Here is CommonReceiver class.
public class CommonReceiver extends BroadcastReceiver {
public void onReceive(Context paramContext, Intent paramIntent)
{
paramContext.startService(new Intent(paramContext, FileObserverService.class));
}
}
Here is its definition in AndroidManifest.xml just before application closing tag.
<receiver android:name="com.alexpap.services.CommonReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT"/>
</intent-filter>
</receiver>
Start service in StartServicesActivity activity.
Intent iFileObserver = new Intent(StartServicesActivity.this, FileObserverService.class);
StartServicesActivity.this.startService(iFileObserver);
Here is onStartCommand() method of the service.
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
/*** Put your code here ***/
startServiceForeground(intent, flags, startId);
return Service.START_STICKY;
}
public int startServiceForeground(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, StartServicesActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("File Observer Service")
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(300, notification);
return START_STICKY;
}
I tested this code using Task Killer app, and each time the service was killed, it was restarted again almost immediately (performs onStartCommand()). It is restarted also each time you turn on the phone and after rebooting.
I use this code in my application, which emails every picture you take with your phone to predefinde list of emails. The sending email and list of receiving emails are set in another activity and are stored in Shared Preferences. I took about 100 pictures in several hours and all they were sent properly to receiving emails.
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, YourService.class));
}
write above code in your service and your service will never stop even user want to destroy it or they want to kill it it will never kill untill your app not get uninstall from your device
You can try to start your service repeatedly, for example every 5 sec.
This way, when your service is running, it will perform onStartCommand() every 5 sec. I tested this scheme and it is very reliable, but unfortunately it increases slightly phone overhead.
Here is the code in your activity where you start the service.
Intent iFileObserver = new Intent(StartServicesActivity.this, FileObserverService.class);
PendingIntent pendingIntentFileObserver = PendingIntent.getService(StartServicesActivity.this, 0, iFileObserver, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Date now = new Date();
//start every 5 seconds
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, now.getTime(), 5*1000, pendingIntentFileObserver);
And here is onStartCommand() of the service.
//class variable
public static boolean isStarted = false;
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
//check if your service is already started
if (isStarted){ //yes - do nothing
return Service.START_STICKY;
} else { //no
isStarted = true;
}
/**** the rest of your code ***/
return Service.START_STICKY;
}
First create service in another process, and write broadcaster which runs in recursion in time intervals
protected CountDownTimer rebootService = new CountDownTimer(9000, 9000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
sendBroadcast(reboot);
this.start();
Log.d(TAG, "rebootService sending PREVENT AUTOREBOT broadcast");
}
};
After that register broadcast receiver in main process also with timer recursion that is launched after first broadcast from service arrived
protected static class ServiceAutoRebooter extends BroadcastReceiver {
private static ServiceAutoRebooter instance = null;
private RebootTimer rebootTimer = null;
private static ServiceAutoRebooter getInstance() {
if (instance == null) {
instance = new ServiceAutoRebooter();
}
return instance;
}
public class RebootTimer extends CountDownTimer {
private Context _context;
private Intent _service;
public RebootTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
_context.startService(_service);
this.cancel();
Log.d(TAG, "Service AutoRebooted");
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (rebootTimer == null) {
Log.d(TAG, "rebootTimer == null");
rebootTimer = new RebootTimer(10000, 10000);
rebootTimer._context = context;
Intent service = new Intent(context, SomeService.class);
rebootTimer._service = service;
rebootTimer.start();
} else {
rebootTimer.cancel();
rebootTimer.start();
Log.d(TAG, "rebootTimer is restarted");
}
}
}
Service will be auto-rebooted if time at RebootTimer (main process) expires, which means that "PREVENT AUTOREBOT" broadcast from service hasn't arrived
i found a solution .... late answer but i wanted to answer...
we can send a broadcast in the ondestroy of the service and create a receiver that receives the broadcast and starts the service again.... when it is destroyed by any reasons...
pls try following:
final Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
default:
super.handleMessage(msg);
}
}
}
#Override
public void onCreate() {
super.onCreate();
makeServiceForeground();
}
#Override
public IBinder onBind(Intent arg0) {
return mMessenger.getBinder();
}
private void makeServiceForeground() {
IActivityManager am = ActivityManagerNative.getDefault();
try {
am.setProcessForeground(onBind(null), android.os.Process.myPid(), true);
} catch (RemoteException e) {
Log.e("", "cant set to foreground" + e.toString());
}
}
also need add in manifest.xml
<uses-permission android:name="android.permission.SET_PROCESS_LIMIT"/>