I need to create a service that allow my application to work also when I close it, I’ve tried with STICKY_SERVICE but it doesn’t work... if anyone can decribe me how I can do this please answer this question.
It works with android 7.1 and it doesn’t with other versions
Here is my code...
public class SensorService extends Service {
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
stoptimertask();
Intent broadcastIntent = new Intent("RestartSensor");
sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my service Restarter...
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops");
context.startService(new Intent(context, SensorService.class));
}
}
And the mainClass
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private SensorService mSensorService;
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
mSensorService = new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
#Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
}
This restartthe service correctly but after 3/4 seconds it die.
I've added this to my manifest
<service
android:name=".SensorService"
android:enabled="true" >
</service>
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="RestartSensor"/>
</intent-filter>
</receiver>
Add the following code to your sensor service and edit as per your need. You need to bind the sticky service to a notification to keep the service alive and start in the foreground.
#Override
public void onCreate() {
super.onCreate();
Intent notifIntent = new Intent(this, SensorService.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, notifIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.smslogo_100x100)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText("Running")
.setContentIntent(pi)
.build();
startForeground(101010, notification);
}
This will rectify the issue you are facing and the service will run forever.
Related
I'm developing an app that is going to require 2 services:
HostService - A foreground service that manages music playback using the Spotify app-remote SDK. It is necessary to run this service in the foreground as I need to detect playState changes and manage playback constantly. However, this service ONLY needs to run if a condition is met, we'll call that condition isHost. This service will be bound to a SessionActivity that displays the music playing and manages playback.
ApiService - A service that continuously polls a separate web API for updates. This must also run in the foreground if the isHost condition is met as the updates may influence the music playback. However, if the user is not a host, this can be a background process that only needs to poll while the user is actively using a particular Activity. I'm not sure if this service should also be bound to the activity or not.
My question is, how should I go about setting up the ApiService differently depending on this condition? I've started to implement these services below but I'm not entirely sure what I have done makes sense. Additionally, am I doing the right thing by using an event handler the way I am? I don't fully understand Intents and I'm not sure if I should be using broadcast messages and such instead.
SessionActivity.java
class SessionActivity extends AppCompatActivity implements HostEventHandler, ApiEventHandler {
private boolean isHost;
private String data;
private String UID;
private ApiService api;
private HostService host;
private boolean hostBound;
private boolean apiBound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_session);
isHost = getIntent().getBooleanExtra("isHost", false);
data = getIntent().getStringExtra("data");
UID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
}
private ServiceConnection hostConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(Constants.TAG, "Bound to HostService");
HostService.LocalBinder binder = (HostService.LocalBinder) service;
host = (HostService) binder.getService()
host.registerEventHandler(this);
hostBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.e(Constants.TAG, "onServiceDisconnected");
hostService = null;
}
};
private ServiceConnection apiConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(Constants.TAG, "Bound to ApiService");
HostService.LocalBinder binder = (ApiService.LocalBinder) service;
api = (ApiService) binder.getService()
api.registerEventHandler(this);
apiBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.e(Constants.TAG, "onServiceDisconnected");
apiService = null;
}
};
protected void onStart() {
super.onStart();
Log.d(Constants.TAG, "Binding to services...");
Intent intent = new Intent(this, ApiService.class);
intent.putExtra("data", data);
intent.putExtra("user", Constants.UID);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
if (isHost) {
Intent intent = new Intent(this, HostService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
{
}
#Override
protected void onStop() {
super.onStop();
unbindService(apiConnection);
apiBound = false;
if (isHost) {
unbindService(hostService);
hostBound = false;
}
}
// HostEventHandler and ApiEventHandler methods...
}
HostService.java
public class HostService extends Service {
private final IBinder binder = new LocalBinder();
private HostEventHandler handler;
public class LocalBinder extends Binder {
HostService getService() {
return HostService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
Log.d(Constants.TAG, "onBind");
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, SessionActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Foreground service is running...")
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
connect(); // This connects to spotify
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
disconnect();
}
public registerEventHandler(HostEventHandler handler) {
this.handler = handler;
}
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);
}
}
}
ApiService.java
public class ApiService extends Service {
private final IBinder binder = new LocalBinder();
private ApiEventHandler handler;
private final Timer timer;
private boolean connected = false;
private String data;
private String UID;
private ApiState state;
public class LocalBinder extends Binder {
HostService getService() {
return ApiService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
Log.d(Constants.TAG, "onBind");
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!connected) {
data = intent.getStringExtra("data");
UID = intent.getStringExtra("user");
connect();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
disconnect();
}
public void registerEventHandler(ApiEventHandler handler) {
this.handler = handler;
}
public ApiState getState() {
return state;
}
private void connect() {
if (connected) return;
class Updater extends TimerTask {
#Override
public void run() {
state = fetchUpdatedState(); // This will implement the web request
handler.onStateUpdate(state);
Log.d(Constants.TAG, "Polling API...");
timer.schedule(new Updater(), Constants.REFRESH_DELAY);
}
}
timer.schedule(new Updater(), Constants.REFRESH_DELAY);
connected = true;
}
}
I have developed an Android app that has a background service that runs endlessly and saves on a local SqLite DB the results of bluetooth scan and GPS positions. Only on Huawei devices this service seems to be paused or stopped for some minutes (I noticed that after inserting some log into the code): in theese minutes any log is written.
. I tried without success to change some settings of device (battery optimization).
Do you have some advice to solve the problem?
Below you can find a snipped of the service.
public class MyService extends Service {
public MyService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
...
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(1031, getNotification());
}
final Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);
ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
MyServiceBinder binder = (MyServiceBinder) service;
started = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
started = false;
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
}
#RequiresApi(Build.VERSION_CODES.O)
private Notification getNotification() {
NotificationChannel channel = new NotificationChannel("channel_01", "My Channel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(getApplicationContext(), "channel_01");
builder.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText(getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_stat_onesignal_default);
return builder.build();
}
public class MyServiceBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
private void stopForegroundService()
{
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
#Override
public void onDestroy() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForegroundService();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Restart after 5 secs
Handler h = new Handler(Looper.getMainLooper());
h.postDelayed(new Runnable() {
#Override
public void run() {
GenericUtility.launchService(MyService.class, getApplication());
}
}, 5000);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
...
initScanLoop();
initLocationManager();
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return new MyServiceBinder();
}
#Override
public boolean onUnbind(Intent intent) {
boolean res = super.onUnbind(intent);
return res;
}
/*Init bluetooth handler*/
private void initScanLoop() {
final Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
scanLeDevice();
hBeacon.postDelayed(this, SCAN_DURATION + 10000);
}
});
}
private void scanLeDevice() {
if(mLEScanner != null && !scanning.get() && !stopScan) {
scanning.set(true);
mLEScanner.startScan(null, settings, mScanCallback);
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(scanning.get()) {
stopScanLeDevice();
}
}
}, SCAN_DURATION);
}
}
private void stopScanLeDevice() {
scanning.set(false);
if(mLEScanner != null) {
mLEScanner.stopScan(mScanCallback);
}
}
/*Finish bluetooth handler*/
/*Init GPS handler*/
private void initLocationManager() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
createLocationChangedCallback();
locationListener = new BeaconScanLocationListener(locationChangedCallback);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
private void createLocationChangedCallback() {
locationChangedCallback = new LocationChangedCallback() {
#Override
public void callback(final Location location) {
try {
//GPS callcback
} catch(Exception e) {
}
}
#Override
public void enabledDisabled(boolean enabled) {
}
};
}
/*Finish GPS handler*/
}
UPDATE
I improved app functionality replacing bluetooth scanning with monitoring beacon in region function of Android Beacon Library.
You have to configure in settings for app can run in background for Huawei
you can check out this link here
This problem can you fix it by put your device in App launch normally the app manage by Huawei but you must make it manage manually after that Huawei can't put the service in sleep mode.
This question already has an answer here:
Want to Access Power Button events in android [duplicate]
(1 answer)
Closed 4 years ago.
I am developing an application in which call on an number on power button click (4 times) but now issue is when user press home button 4 times it will trigged the call and I want only side power button click.
My receiver and service in manifest
<receiver
android:name=".services.SOSBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
<service
android:name=".services.SOSService"
android:enabled="true">
</service>
and my BroadcastReceiver class
public class SOSBroadcastReceiver extends BroadcastReceiver
{
private static long lastTriggerTime = 0;
private static final int ONE_MILLI = 1000;
protected static final long ONE_SEC = 1 * ONE_MILLI;
protected static final long TWO_SEC = 2 * ONE_MILLI;
protected static final long THREE_SEC = 3 * ONE_MILLI;
protected static final int TRIGGER_THRESHOLD = 3;
protected static boolean triggerInProgress = false;
protected static int triggerCounter = 0;
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().contains(Intent.ACTION_SCREEN_ON))
{
if (!triggerInProgress)
{
checkAndCreateAlert(context);
}
}
else if (intent.getAction().contains(Intent.ACTION_SCREEN_OFF))
{
if (!triggerInProgress)
{
checkAndCreateAlert(context);
}
}
}
private void checkAndCreateAlert(Context context)
{
/*---- If the gap between power button press is less than 2 seconds ----*/
if ((System.currentTimeMillis() - lastTriggerTime) <= TWO_SEC
|| (triggerCounter == 0))
{
triggerCounter++;
lastTriggerTime = System.currentTimeMillis();
}
else
{
triggerCounter = 0;
}
if (triggerCounter > TRIGGER_THRESHOLD)
{
((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(1000);
triggerInProgress = true;
Intent intent = new Intent(context, SOSActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("timer", true);
context.startActivity(intent);
triggerInProgress = false;
triggerCounter = 0;
}
}
}
My code will keep the count of power button click in terms of screen_on and screen_off event and execute the other method if power button is pressed more than 3 time in 2secs.
This is my Service class
public class SOSService extends Service
{
BroadcastReceiver mReceiver;
IntentFilter pqrs_intentFilter;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public void onDestroy()
{
unregisterReceiver(mReceiver);
}
#Override
public void onStart(Intent intent, int startid)
{
pqrs_intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
pqrs_intentFilter.addAction(Intent.ACTION_SCREEN_ON);
mReceiver = new SOSBroadcastReceiver();
registerReceiver(mReceiver, pqrs_intentFilter);
}
public void onStop(Intent intent)
{
unregisterReceiver(mReceiver);
}
}
public class ExampleActivity extends Activity {
#Override
protected void onCreate() {
// INITIALIZE RECEIVER
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// YOUR CODE
}
#Override
protected void onPause() {
// WHEN THE SCREEN IS ABOUT TO TURN OFF
if (ScreenReceiver.wasScreenOn) {
// THIS IS THE CASE WHEN ONPAUSE() IS CALLED BY THE SYSTEM DUE TO A SCREEN STATE CHANGE
System.out.println("SCREEN TURNED OFF");
} else {
// THIS IS WHEN ONPAUSE() IS CALLED WHEN THE SCREEN STATE HAS NOT CHANGED
}
super.onPause();
}
#Override
protected void onResume() {
// ONLY WHEN SCREEN TURNS ON
if (!ScreenReceiver.wasScreenOn) {
// THIS IS WHEN ONRESUME() IS CALLED DUE TO A SCREEN STATE CHANGE
System.out.println("SCREEN TURNED ON");
} else {
// THIS IS WHEN ONRESUME() IS CALLED WHEN THE SCREEN STATE HAS NOT CHANGED
}
super.onResume();
}
}
Receiver
public class ScreenReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Service
public static class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// YOUR CODE
} else {
// YOUR CODE
}
}
}
Hopefully this was useful. Let me know if you have questions.
I'm new at Android,
so please excuse my low experience.
I need this service to check if BroadcastReceiver is running or not every period of time.
If it's running then I want it to do nothing, but if not running I want it to run it.
In this code the service run the receiver every 20 sec, but it didn't check if receiver running or not, so every 20 sec I will get new receiver and the running receiver.
Any idea to solve this problem please?
Receiver.java
public class Receiver extends BroadcastReceiver
{
int numberr =0;
private static final String TAG = "RestartServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
int delay = 0;
int period = 10000;
Timer basic_timer = new Timer();
basic_timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.e("view", ""+numberr );
numberr++;
}
}, delay, period);
}
}
Service1.java
public class Service1 extends Service {
public Service1() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int delay = 0;
int period =20000;
Timer basic_timer = new Timer();
basic_timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
sendBroadcast(new Intent("run"));
}
}, delay, period);
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I think u just forget to register the receiver in menifest.
try to add this beside service in menifest~
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="run" />
</intent-filter>
</receiver>
<service ...
ps. make sure your service has been started . or try to call this in your activity
startService(new Intent(this, Service1.class));
I'm doing an app that checks the live scores. I don't know if it's the best way, but I created a Timertask, a Service and and Activity to notify.
The Timertask checks every x seconds if the score changes and if it changes, informs the Service.
If the Service is informed, it calls the Activity that will notify the user. My problem is I failed at calling the activity to Notify from the Service.
Here is my code (For the example, I didn't take the score but a variable i.
//import ...
public class MyService extends Service{
Notif notif = new Notif();
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
Timer time = new Timer(); // Instantiate Timer Object
final ScheduleTask st = new ScheduleTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 5000); // Create Repetitively task for every 1 secs
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
public void checkI(int i){
if (i==3){
notif.initializeUIElements();
}
}
}
TimerTask
import ...
// Create a class extends with TimerTask
public class ScheduleTask extends TimerTask {
MyService myService = new MyService();
Notif notif = new Notif();
int i = 0;
// Add your task here
public void run() {
i++;
System.out.println("affichage numero " + i );
myService.checkI(i);
}
public int getI() {
return i;
}
}
Notif
import ...
public class Notif extends Activity {
private static final int NOTIFY_ME_ID = 1987;
private NotificationManager mgr = null;
ScheduleTask scheduleTask = new ScheduleTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
void initializeUIElements() {
Notification note = new Notification(R.drawable.ic_launcher,
"Welcome to MyDoople.com", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);
note.setLatestEventInfo(this, "MyDoople.com", "An Android Portal for Development",
i);
// note.number = ++count;
note.flags |= Notification.FLAG_ONGOING_EVENT;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Services may be terminated by the system if resources are needed. For your requirement, it's best to use AlarmManager to periodically do something.
Here are more references: [1], [2]