简体   繁体   中英

android service continue after shutdown

I have the service InfoReceiver . This service starts when the application starts and still be running when the application is closed.Also i have added the application to start on boot completed.The service will call the code i want every 82 milliseconds(24 hours). I don't know how to make thread sleep while the phone is shutdown. Also i want to destroy completed the service after 120 hours. here is my code

Thank you in advance!

InfoReceiver.java

 public class InfoReceiver extends Service {

        @Override
        public void onCreate()
        {
            super.onCreate();



                   //do something code


                }

                            }

MyBroadcastreceiver.java

public class MyBroadcastReceiver extends BroadcastReceiver {
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
    mContext = context;
     Calendar cal = Calendar.getInstance();
     // add 5 minutes to the calendar object
     cal.add(Calendar.SECOND, 84000);
     Intent startServiceIntent = new Intent(context, InfoReceiver.class);
     PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startServiceIntent, 0);
     AlarmManager am = (AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE); 
     am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), startPIntent);


}



}

Manifest file

<service android:name=".InfoReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name=".InfoReceiver"/>

        </intent-filter>
</service>
<receiver  android:process=":remote" android:name=".MyBroadcastReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>

You shouldn't be using a thread sleep for this. The system will quickly kill off your service (in a relative sense of things, 24 hours is a long time to have the same app in memory). Instead you should be using an AlarmManager and request that your app has an intent fired so that you can do work every day. On boot, register the AlarmManager to do work every few days. Also, whenever you do a bit of work, save how long you've up (perhaps in a SharedPreferences), so you can know to stop requesting updates from the AlarmManager after that much time. This will get you a design where your app can go out of memory and die off -- safely absolving you of any memory killing complaints -- and then do work again when necessary.

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