AlarmManager or Service

后端 未结 1 1139
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 09:12

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 ap

1条回答
  •  一整个雨季
    2021-01-03 09:42

    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.

    0 讨论(0)
提交回复
热议问题