Android uses IntentService to execute background tasks, androidintent
IntentService provides a way to execute tasks in background threads and is suitable for processing background tasks with long execution time.
Advantages:
(1) IntentService runs in a separate thread and does not block the UI thread
(2) IntentService is not affected by the lifecycle.
Disadvantages:
(1) You cannot directly interact with the UI. You can use Broadcast.
(2) requests are executed sequentially. The second request can be executed only after the first request is executed.
(3) requests cannot be interrupted
Steps for using IntentService:
(1) start the service through startService in the Activity and pass parameters.
(2) receive parameters in the Service, perform time-consuming processing, complete processing, send Broadcat, and pass the processing result
(3) Register BroadcastReceiver in the Activity, listen to broadcasts, and update the UI.
Let's look at an example:
Public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button btn = (Button) this. findViewById (R. id. btn); btn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// start the service through startService and pass parameters. Intent mServiceIntent = new Intent (MainActivity. this, RSSPullService. class); mServiceIntent. setData (Uri. parse ("http://www.baidu.com/"); MainActivity. this. startService (mServiceIntent) ;}}); // register BroadcastReceiver and listen to broadcast IntentFilter statusIntentFilter = new IntentFilter (Constants. BROADCAST_ACTION); // Sets the filter's category to DEFAULT statusIntentFilter. addCategory (Intent. CATEGORY_DEFAULT); DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver (); // Registers the DownloadStateReceiver and its intent filtersLocalBroadcastManager. getInstance (this ). registerReceiver (mDownloadStateReceiver, statusIntentFilter);} private class DownloadStateReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {String data = intent. getStringExtra (Constants. EXTENDED_DATA); Log. e ("test", data); Toast. makeText (context, data, Toast. LENGTH_SHORT ). show ();}}}
Public class RSSPullService extends IntentService {public RSSPullService () {super ("RSSPullService") ;}@ Overrideprotected void onHandleIntent (Intent workIntent) {// receives parameters for time-consuming processing, after processing, send BroadcatString localUrlString = workIntent. getDataString (); String data = download (localUrlString); Intent localIntent = new Intent (Constants. BROADCAST_ACTION); // Puts the status into the IntentlocalIntent. putExtra (Consta NT. EXTENDED_DATA, data); // Broadcasts the Intent to receivers in this app. localBroadcastManager. getInstance (this ). sendBroadcast (localIntent);} private String download (String localUrlString) {try {URL url = new URL (localUrlString); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); InputStream in = conn. getInputStream (); ByteArrayOutputStream out = new ByteArrayOutputStream (); byte [] buf F = new byte [1024]; int len = 0; while (len = in. read (buff ))! =-1) {out. write (buff, 0, len);} in. close (); return new String (out. toByteArray ();} catch (Exception e) {e. printStackTrace (); return "";}}}
public class Constants {// Defines a custom Intent actionpublic static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST";// Defines the key for the status "extra" in an Intentpublic static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS";public static final String EXTENDED_DATA = "com.example.android.threadsample.DATA";}
AndroidManifest. xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.intentservicedemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" /> <!-- Requires this permission to download RSS data from Picasa --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Defines the application. --> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.example.android.intentservicedemo.MainActivity" android:label="@string/activity_title" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- No intent filters are specified, so android:exported defaults to "false". The service is only available to this app. --> <service android:name="com.example.android.intentservicedemo.RSSPullService" android:exported="false"/> </application></manifest>
Reference: http://developer.android.com/training/run-background-service/index.html
What is the relationship between android activity, intent, and service?
Intent is a bridge between activity and service. It serves as the main interface for communication staff and activity operation display. The service runs in the background and is suitable for long-time running, such as downloading and listening to songs ..
What are the advantages of IntentService in ANDroid?
IntentService is. startService (Intent) starts a Service that can process asynchronous requests. When using this Service, you only need to inherit the IntentService and override the onHandleIntent (Intent) method to receive an Intent object, stop yourself when appropriate (usually when the work is completed ). all requests are processed in one working thread, and they will be executed alternately (but will not block the execution of the main thread). Only one request can be executed at a time.
This is a message-based service. Every time you start this service, it does not process your work immediately, but first creates the corresponding logoff, handler and added the Message object with the client Intent in MessageQueue. When logoff finds a Message, it obtains the Intent object through the onHandleIntent (Intent) msg. obj) to call your processing program. after processing, your services will be stopped. this means that the life cycle of Intent is consistent with that of the task you process. therefore, this type of download task is very good. After the download task is completed, the Service stops and exits.