AlarmManager or Service

▼魔方 西西 提交于 2019-12-01 00:19:02

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!