Implementation of Android auto-Start Service

Source: Internet
Author: User

Android auto-start is probably the simplest in the mobile operating system. We only need to listen to a Broadcast (Broadcast) started at the startup. First, write a Receiver (that is, a broadcast listener) that inherits BroadcastReceiver, as shown below:

View source

Print?

Copy codeThe Code is as follows: public class BootReceiver extends BroadcastReceiver {

Private PendingIntent mAlarmSender;

@ Override

Public void onReceive (Context context, Intent intent ){

// Do what you want here (start a Service, Activity, etc.). 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:

View source

Print?

Copy codeThe Code is as follows: <javaser Android: name = ". service. BootReceiver">

<Intent-filter>

<! -- Called after the system is started -->

<Action android: name = "Android. intent. action. BOOT_COMPLETED">

</Action>

</Intent-filter>

</Cycler>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.