We have already talked about Android development: freely choosing TextView text and how to implement TCP and UDP transmission. If you are developing an application that needs to update data in real time and remind users to view new data when there is new data, you need to start a Service in the background, then, you can obtain data from the network in real time. However, if the user shuts down and restarts, your Service may disappear! So how can we ensure that your Service is still active after the boot, and your mobile phone secretly obtains data from the network?
It is very simple. We only need to enable auto-start upon startup. Android auto-start may be the simplest in the mobile operating system. We only need to listen to a Broadcast started upon startup. First, write a Receiver, that is, the broadcast listener), and inherit the BroadcastReceiver, as shown below:
- Public class BootReceiver extends BroadcastReceiver {
- Private PendingIntent mAlarmSender;
- @ Override
- Public void onReceive (Context context, Intent intent ){
- // Start a Service, Activity, and so on. In this example, start a scheduled scheduling program and start a Service every 30 minutes to update data.
- MAlarmSender = PendingIntent. getService (context, 0, new Intent (context,
- RefreshDataService. class), 0 );
- Long firstTime = SystemClock. elapsedRealtime ();
- AlarmManager am = (AlarmManager) context
- . GetSystemService (Activity. ALARM_SERVICE );
- Am. cancel (mAlarmSender );
- Am. setRepeating (AlarmManager. ELAPSED_REALTIME_WAKEUP, firstTime,
- 30x60*1000, mAlarmSender );
- }
- }
Next, we only need to register this handler in the application configuration file AndroidManifest. xml to listen to system startup events, as shown below:
- <Cycler android: name = ". service. BootReceiver">
- <Intent-filter>
- <! -- Called after the system is started -->
- <Action android: name = "android. intent. action. BOOT_COMPLETED">
- </Action>
- </Intent-filter>
- </Cycler>
In this way, the system is automatically started. How can this problem be solved? Is it easy?