Reputation: 7800
I need a confirmation regarding the steps I take in onLowMemory method of service. I have a sticky service. Here is the startCommand:
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
initialiseObjects();
setChatObjects();
return Service.START_STICKY;
}
Here is the OnLowMemory Method:
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
System.gc();
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);
this.stopSelf();
}
Please check it and help me to confirm whether I am doing it in correct way or not. Do I have to restart the service with alarm manager or it will automatically restart as it is a sticky service? Also is it a correct procedure to stop the service using this.stopSelf();
after setting the alarm, in this case will alarm manager properly restart the service after specified time?.
Upvotes: 1
Views: 1339
Reputation: 1022
Though it's a bit late to answer, but still it may help others and also help someone like me who is new in Android Development so i'm sharing my understandings.
First, it is not very well recommended to use 'System.gc()' manually, the system will automatically Collect Garbage that is 'System.gc()' will be called when the heap size will reach it's limit. Manually calling it may cause the app to work a bit slow at significant times.This video explains about Memory Management and also briefly about 'System.gc()' Memory management for Android Apps
Second, yes the service will automatically restart if the service returns START_STICKY shortly after and you don't need alarm manager to do it.
Third, yes this stops the service correctly as I checked. Though, Alarm Manager might not be needed as the Service will automatically restart because of START_STICKY.
Though, depending on your application, under critical conditions of system memory, there is still a chance that the service will be killed and not restart right away.
Upvotes: 0
Reputation: 2782
Perhaps you can override the application's onLowMemory() instead of your service onLowMemory().
public class MyApplication extends Application {
@Override
public void onLowMemory() {
super.onLowMemory();
stopService(new Intent(getApplicationContext(), MyService.class));
startService(new Intent(getApplicationContext(), MyService.class));
}
}
Hope this helps.
Upvotes: 1