Android Service and AndroidService

Source: Internet
Author: User

Android Service and AndroidService

Service in Android

Service Introduction:

A Service is designed to perform operations that take a long time in the background.
Because Android allows the Service to run in the background or even after the Activity is completed, the Service has a higher priority than the Activity.

Create a Service:

To create a basic Service, you need to do the following: 1) create a Java class and let it inherit from Service 2) override onCreate () and onBind () Methods
Here, the onCreate () method is executed when the Service is created, and the onBind () method is executed when the Service is bound.

public class ExampleService extends Service{        @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();    }}

After a new Service is created, it must be configured in the AndroidManifest. xml file. A Service tag must be included in the application node.
<Service android: name = ". ExampleService" android: enabled = "true" android: permission = "exam02.chenqian.com. servicedemo"> </service>
Of course, if you want your custom Service to be used only by the application you write, you can also add: android: permission = "exam02.chenqian.com. servicedemo" in the tag"

Let the Service execute a specific task:

If you want the Service to execute a specific task, you can rewrite the onStartCommand () method of the Service. Note that the onStart () method is not recommended before API15. onStartCommand () the method is executed after the Service onCreate.

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    return super.onStartCommand(intent, flags, startId);}

Start and Stop a Service:

Start a Service explicitly:

// Start ExampleServiceIntent intent = new Intent (this, ExampleService. class); // start ExampleServicestartService (intent );

To facilitate observation, we can add Log. I ("ServiceState", "--------------> is Running") in the onStartCommand () method of the Custom Service class created previously ");
When we call and run MainActivity, we can observe the output in Logcat: I/ServiceState: is Running.
Of course, we can also stop a Service. To better observe the effect, we can re-write the onDestroy () method in the ExampleService class:

    @Override    public void onDestroy() {        Log.i("ServiceState","------------------>Destroy");        super.onDestroy();    }

You can stop a Service in MainActivity as follows:
Show stopping a Service: note that a Service is replaced when writing here, And the Custom Service is located in MyService, which is no longer the previous ExampleService, however, you agree to continue writing as you did before. After all, the methods are the same ;-)

// Disable ServiceIntent serviceIntent = new Intent (MainActivity. this, MyService. class); // disable ServicestopService (serviceIntent );

Note that Service calls cannot be nested. Therefore, no matter how many times a Service is called, a call to stop stopService () terminates the Service that matches the running state.
Because the Service has a high priority, it is generally not terminated at runtime. Therefore, you can use auto-termination to avoid consuming system resources to run the Service in the background. The specific method is to add stopSelf () to the onStartCommand () method. However, note that stopSelf () does not directly terminate the Service, instead of waiting for the system to recycle the Service after all functions or requests of the Service are executed, onDestroy () is called to destroy the Service.

Bind Service to Activity:

When a Service is called in an Activity, it will not be destroyed as the Activity is destroyed, but may continue to run in the background and continue to occupy system resources, therefore, if the Activity is automatically stopped when it is destroyed, it will greatly save the system's resource usage. We can bind the Activity to the Service in the following ways:
XML layout file: four buttons are implemented in the layout file to start, stop, bind, and unbind services respectively :-)

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: id = "@ + id/activity_main" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical" tools: context = "demo.chenqian.com. androidserverdemo. mainActivity "> <! -- Enable Service --> <Button android: id = "@ + id/btnStartService" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_margin = "20dp" android: text = "@ string/startService"/> <! -- Disable Service --> <Button android: id = "@ + id/btnStopService" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_margin = "20dp" android: text = "@ string/stopService"/> <! -- Bind Service --> <Button android: id = "@ + id/btnBindService" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_margin = "20dp" android: text = "@ string/bindService"/> <! -- Unbind Service --> <Button android: id = "@ + id/btnUnbindService" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_margin = "20dp" android: text = "@ string/unbindService"/> </LinearLayout>

MyService class:

Package demo.chenqian.com. androidserverdemo; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; import android. support. annotation. nullable; import android. util. log; public class MyService extends Service {
/* 1. Below we define the internal class MyBinder, which is why we can now define the binder.
2. Here we define binder member variables to achieve transformation */private MyBinder binder = new MyBinder (); @ Override public void onCreate () {Log. d ("ServiceInfo", "created successfully"); super. onCreate () ;}@ Nullable @ Override public IBinder onBind (Intent intent) {Log. d ("ServiceInfo", "bound successfully"); return null ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {Log. d ("ServiceInfo", "Start execution"); return super. onStartCommand (intent, flags, startId) ;}@ Override public boolean onUnbind (Intent intent) {Log. d ("ServiceInfo", "unbound successfully"); return super. onUnbind (intent) ;}@ Override public void onDestroy () {Log. d ("ServiceInfo", "destroyed successfully"); super. onDestroy ();}
/* We know that the Android system isolates every application in the corresponding independent sandbox for security protection and overall stability. Therefore, our custom Service is actually running in
For user space, we have many services that need to reference the system Service. Therefore, how can we implement communication between them in user space and system space? This requires Binder,
The Binder is a method for communication between different processes in the Android system. The Binder itself has the meaning of adhesive. The Binder can bond the four main components in the Android system.
You have created a new internal class of MyBinder in the MyService class, and let it inherit the Binder class to obtain the MyService. In this way, you should know why we want to create a new My-
Member variable of the Binder ^ _ ^. You can also see the use of the relevant instance in the MainActivity below, such as public void onServiceConnected (ComponentName
Name, IBinder service). Note that the service here is of the IBinder type, and we will use it when getting MyService below */
Class MyBinder extends Binder {MyService getService () {Log. d ("ServiceInfo", "the current service instance is obtained successfully"); return MyService. this ;}}}

MainActivity class:

Package demo.chenqian.com. androidserverdemo; import android. content. componentName; import android. content. context; import android. content. intent; import android. content. serviceConnection; import android. OS. binder; import android. OS. IBinder; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; import android. widget. toast; public class MainActivity extends AppCompatActivity implements View. onClickListener {private Context mContext; private Button btnStartService; private Button btnStopService; private Button btnBindService; private Button btnUnbindService; private MyService myService; private Intent serviceIntent; private boolean isBond;
/* IsBond: this variable is used to identify whether the current Activity and Service are being bound, because if it is not identified, if the Activity does not
Binding to the Service, and unbinding will result in an error or an exception, because Android does not allow binding to null */
/* Note: here we have created a connection and overwritten the related method. Why should we create this connection? It is because of the binding and unbinding at the bottom.
Method: bind and unbind require a connection. The first method is to facilitate observation, and the other is to close the connection successfully or lost.
Perform related custom tasks or operations */private ServiceConnection connection = new ServiceConnection () {@ Override public void onServiceConnected (ComponentName, IBinder service) {Log. d ("ServiceState", "connection successful"); myService = (MyService. myBinder) service ). getService () ;}@ Override public void onServiceDisconnected (ComponentName name) {Log. d ("ServiceState", "Disconnect ");
// When the connection points to an instance that is null and has no guidance, the instance will be reclaimed by the virtual machine, reducing the occupied resource myService = null ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // initialize the data mContext = this; isBond = false; // introduce the required component btnStartService = (Button) findViewById (R. id. btnStartService); btnStopService = (Button) findViewById (R. id. btnStopService); btnBindService = (Button) findViewById (R. id. btnBindService); btnUnbindService = (Button) findViewById (R. id. btnUnbindService); // click the button to add the event btnStartService. setOnClickListener (this); btnStopService. setOnClickListener (this); btnBindService. setOnClickListener (this); btnUnbindService. setOnClickListener (this) ;}@ Override protected void onStart () {serviceIntent = new Intent (this, MyService. class); super. onStart () ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btnStartService: // enable Service startService (serviceIntent); break; case R. id. btnStopService: // disable Service stopService (serviceIntent); break; case R. id. btnBindService: // bind Service isBond = bindService (serviceIntent, connection, Context. BIND_AUTO_CREATE); break; case R. id. btnUnbindService: // unbind a Service. if the connection is null, an error is returned. if (isBond) {unbindService (connection); // if the binding is successful, change the connection ID to false isBond = false;} break ;}}}

AndroidManifest. xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="demo.chenqian.com.androidserverdemo">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".MyService" android:enabled="true" android:permission="demo.chenqian.com.androidserverdemo"></service>    </application></manifest>

About the future:

1. I feel that the Binder section is not clear to everyone. I will study it further and complete it.
2. If you have time to compile an example of playing music in the background, you can refer to it.

 

 



 

 

 

 

 

 

 

Related Article

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.