Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlarmManager or Service

I'm a C++ developer and developing my first Android application. My application is an special kind of Reminder. I'm looking for the best way to do it. I have tried this approaches:

  1. Use a Service
  2. Use an AlarmManager

My question is that can I use AlarmManager singly? Is it a CPU time consuming task considering that my AlarmManager should be fired every 1 second ? (It seems that every time an AlarmManager is executed a new process except main process is created and immediately is killed).

If I use a service then my application should always stay in memory and also what happens if is killed by user !?

How Android Alarms (default installed application) works?

Any help would be appreciated.

like image 838
mh taqia Avatar asked Feb 15 '23 21:02

mh taqia


1 Answers

Use a Service that returns START_STICKY and make it startForeground, this way your app will run all the time even if System kills it for resources after a while it'll be up and running again normally, and about user killing it well this is something even big apps complain about like Whatsapp as u see in the wornings when installing whatsapp first time. here is an example of how the service should be like:

 public class Yourservice extends Service{

@Override
public void onCreate() {
    super.onCreate();
    // Oncreat called one time and used for general declarations like registering a broadcast receiver  
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    super.onStartCommand(intent, flags, startId);

// here to show that your service is running foreground     
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent bIntent = new Intent(this, Main.class);       
    PendingIntent pbIntent = PendingIntent.getActivity(this, 0 , bIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
    NotificationCompat.Builder bBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("title")
                .setContentText("sub title")
                .setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pbIntent);
    barNotif = bBuilder.build();
    this.startForeground(1, barNotif);

// here the body of your service where you can arrange your reminders and send alerts   
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopForeground(true);
}
}

this is the best recipe for ongoing service to execute your codes.

like image 86
3lomahmed Avatar answered Feb 27 '23 17:02

3lomahmed