Android One of the four Components service introduction-android Learning Journey (12)

Source: Internet
Author: User

Basic concepts:

Service is one of Android's four components, running in the background to perform time-consuming operations and does not provide a user interface. Other components, such as acticity, can start the component through StartService, or it can be started by Bindservice and will bind the component for communication.

Usage Scenarios

Background download files, and play music and so on

Attention

The service runs in the main thread, he does not create his own thread, and is not running in a separate thread, so when used, it is necessary to create the thread yourself instead of using it directly, resulting in a ANR error.

Two forms of service

Started service
Other components, such as activity, start the component through Stratservice and so on, and have a separate life cycle that does not depend on the component that launches it.
Bound service
Other components establish a connection through bindservice in order to establish a long-time connection with the service. And can interact with it (sending requests, accepting responses). Its life cycle relies on binding his components, but unbinding them will die.

Code for two service:
 PackagePeng.liu.testview;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.IBinder; Public  class myservice extends Service {     Public MyService() {    }@Override     Public void onCreate() {Super. OnCreate (); ServiceClass SC =NewServiceClass ();    Sc.start (); }Private  class serviceclass extends Thread{        @Override         Public void Run() {Super. Run (); for(inti =0;i< +; i++) {System.out.println ("Hello"+i);Try{Thread.Sleep ( +); }Catch(Exception e)                {E.printstacktrace (); }            }        }    }@Override     PublicIBinderOnbind(Intent Intent) {//Todo:return The communication channel to the service.        Throw NewUnsupportedoperationexception ("not yet implemented"); }}
Another service is
 PackagePeng.liu.testview;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportJava.util.Random; Public  class MyService2 extends Service {     Public MyService2() {    }//First step implementation Binder subclass     Public  class liubinder extends Binder {        //Create a public method that returns the service instance         PublicMyService2GetService(){returnMyService2. This; }    }The //onbind method returns a Liubinder    PrivateLiubinder Binder =NewLiubinder ();@Override     PublicIBinderOnbind(Intent Intent) {returnBinder }//Create a custom business method that must be public     Public int Getrandom() {Random random =NewRandom ();returnRandom.nextint ( -); }@Override     Public void OnDestroy() {Super. OnDestroy (); System.out.println ("Service Done"); }}
Code for the main class:
 PackagePeng.liu.testview;Importandroid.app.Activity;ImportAndroid.content.ComponentName;ImportAndroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public  class mainactivity extends Activity implements View. Onclicklistener {    PrivateButton Send,reg,unreg;PrivateMYSERVICE2 Service;BooleanIsbound;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (r.id.send). Setonclicklistener ( This); Findviewbyid (R.id.reg). Setonclicklistener ( This); Findviewbyid (R.id.unreg). Setonclicklistener ( This); }@Override     Public void OnClick(View view) {Switch(View.getid ()) { CaseR.id.send:startservice (NewIntent (mainactivity. This, Myservice.class)); Break; CaseR.id.reg:intent Intent =NewIntent (mainactivity. This, Myservice2.class);        Bindservice (intent,conn,bind_auto_create); } toast.maketext (mainactivity. This,"Random number is"+service.getrandom (), Toast.length_long). Show (); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Unbindservice (conn); }PrivateServiceconnection conn =NewServiceconnection () {@Override         Public void onserviceconnected(ComponentName componentname, IBinder IBinder)            {Myservice2.liubinder binder = (myservice2.liubinder) IBinder;            Service = Binder.getservice (); Isbound =true; }@Override         Public void onservicedisconnected(ComponentName componentname) {Isbound =false; }    };}

To register the service code:

<service  android:name  =".            MyService " android:enabled  =" true " android:exported  = "true" ;  </service ;  <service  android:name  = ". M            YService2 " android:enabled  =" true " android:exported  = "true" ;  </service ;  

One of the four components of Android service Introduction-android Learning Journey (12)

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.