简体   繁体   中英

how to run service all time in android?

   Can someone explain what problem in this code.

Example code:   

    Intent alarm = new Intent(this.cons, AlarmReceiver.class);
                boolean alarmRunning = (PendingIntent.getBroadcast(this.cons, 0, alarm,
        PendingIntent.FLAG_NO_CREATE) != null);
        if (alarmRunning == false) {
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.cons,
                            0, alarm, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                            SystemClock.elapsedRealtime(), 30000, pendingIntent);
                     ComponentName receiver = new ComponentName(cons, AlarmReceiver.class);
         PackageManager pm = cons.getPackageManager();
         pm.setComponentEnabledSetting(receiver,
                                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                                PackageManager.DONT_KILL_APP);   
            }

this the service start using code. it's worked but once remove the app in heap space in device. it doesn't run. again launch time it will be executed. How it will be run all time ?

I think you may want to run the service in foreground. That way the service is running even when you close the app. There is a notification bar seen until the service is ended (More info here: https://developer.android.com/guide/components/services.html#Foreground )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM