"Android" 16.4 Intentservice class

Source: Internet
Author: User

Category: C #, Android, VS2015;

Date Created: 2016-03-01 I. INTRODUCTION

To further simplify the use of the intent filter, the Android system also provides a Intentservice class, so that you do not need to rewrite other methods, directly implement a class that inherits from Intentservice, Then rewrite the Onhandleintent method.

The Intentservice class inherits from the service class. This class automatically uses worker threads to process all service start-up requests (that is, each request to Intentservice automatically starts a thread to process it).

Because most started services do not require "concurrency" to handle multiple requests (which is actually a risky multithreaded scenario), the best way to do so might be to use the Intentservice class to implement your service.

In short, as long as the started service does not require "concurrent" processing of multiple requests, the preferred approach is to use Intentservice to implement.

1. Working mechanism of Intentservice

Intentservice will automatically perform the following steps:

Creates a default worker thread that executes all intent sent to the Onstartcommand method independently of the main thread of the application.

Create a work queue, and each time you pass in a intent to your onhandleintent (), you'll never have to worry about multithreaded issues.

After all the start requests are processed, the service is terminated, so you never need to call the Stopself method.

Provides the default onbind () implementation code, which returns NULL.

Provides the default Onstartcommand () implementation code, which sends the intent into the work queue and is later passed to your onhandleintent () implementation code.

All of the above steps will be a result: all you have to do is implement Onhandleintent () to complete the task submitted by the client. (Of course, you also need to provide a small section of the construction method for the service.) )

2. Implement Onhandleintent method

The code to implement the Intentservice request is simple, and the job you have to do is to override the Onhandleintent () method in the custom inherited from the Intentservice class, which automatically receives the intent of each boot request, The work of the intent request is then automatically completed in the background.

The following code demonstrates how to override the Onhandleintent () method:

[Service][intentfilter (New string[]{"Com.xamarin.DemoIntentService"})] Public classdemointentservice:intentservice{ PublicDemointentservice ():Base("Demointentservice")    {    }    protected Override voidonhandleintent (Android.Content.Intent Intent) {Console.WriteLine ("perform some long running work"); Console.WriteLine (" Work Complete"); }}

The difference between a class that inherits from Intentservice and a custom class that inherits from a service is that a class that inherits from Intentservice needs to pass the constructor to a string in the base class, which is the function of identifying the internal worker thread.

From the internal implementation code, Intentservice actually puts each request sent by each intent into a work queue, and then processes each request in the work queue separately in different threads, because these intent are run in a separate thread that differs from the main thread. Of course, the main thread is not blocked from running.

When a intent is processed, Intentservice automatically calls the Stopself method to stop the intent immediately.

In short, with intentservice, we do not need to explicitly create a separate thread in the service, nor do we need to terminate the thread we created in the overridden OnDestroy method, some of which are automatically implemented by the Intentservice class. All you need to do is focus on the functionality implemented in the service. Second, example 3--indentservicedemo

Run

Main design Steps

(1) Add Ch1603_main.axml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">    <ButtonAndroid:id= "@+id/ch1603startservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Start Service" />    <ButtonAndroid:id= "@+id/ch1603stopservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Stop Service" /></LinearLayout>

(2) Add Ch1603ServiceDemo.cs

usingSystem;usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.widget;usingSystem.Threading;namespacemydemos.srcdemos{[Service] [Intentfilter (New string[] {action})]  Public classCh1603servicedemo:intentservice { Public Const stringAction ="Mydemos.ch1603service";  PublicCh1603servicedemo ():Base("Ch1603servicedemo")        {        }        protected Override voidonhandleintent (Intent Intent) {varMyHandler =NewHandler (Mainlooper); Myhandler.post (()={Toast.maketext ( This,"Service is started", Toastlength.short).            Show ();            });  for(inti =1; I <=Ten; i++)            {                varmsg =string. Format ("This is the first {0} message from the service", i); Thread.Sleep (Timespan.fromseconds (4)); Myhandler.post (()={Toast.maketext ( This, MSG, toastlength.short).                Show ();            }); }        }         Public Override voidOnDestroy () {Base.            OnDestroy (); NewHandler (Mainlooper). Post (() ={Toast.maketext ( This,"service is stopped", Toastlength.short).            Show ();        }); }    }}

(3) Add Ch1603MainActivity.cs

usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.widget;namespacemydemos.srcdemos{[Activity (Label="ch1603mainactivity")]     Public classch1603mainactivity:activity {protected Override voidOnCreate (Bundle savedinstancestate) {Base.            OnCreate (savedinstancestate);            Setcontentview (Resource.Layout.ch1603_Main); varStart = findviewbyid<button>(Resource.Id.ch1603StartService); Start. Click+=Delegate{StartService (NewIntent (ch1603servicedemo.action));            }; varStop = findviewbyid<button>(Resource.Id.ch1603StopService); Stop. Click+=Delegate{StopService (NewIntent (ch1603servicedemo.action));        }; }    }}

"Android" 16.4 Intentservice class

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.