Service Learning notes, webservice learning notes 2

Source: Internet
Author: User

Service Learning notes, webservice learning notes 2

1. What is Service?

As one of the four major Android components, Service plays an important role. The Service and Activity levels are the same, but there is no interface. It is a Service running on the background. This running "background" is invisible, not in the background thread. In fact, all four components are running in the UI thread, they cannot perform time-consuming operations or network requests in their respective lifecycle methods.

2. How to Use Service

Services can be divided into Local Service and Remote Service. Here we take the common Local Service as an example to introduce the two methods of using the Service.

(1) start the Service through Context. startService () and end the Service through Context. stopService.

Create a new MyService class that inherits services, override the onCreate (), onStartCommand (), and onDestroy () methods, and then set two buttons in MainActivity to add their respective click events to start and stop MyService.

Package com. example. haisun. myapplication3; 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;/*** Created by HaiSun on 2015/10/10. */public class MyService extends Service {@ Nullable @ Override public IBinder onBind (Intent intent) {return null ;}@ Override public void onCreate () {super. onCreate (); Log. d ("MyService", "onCreate executed") ;}@ Override public int onStartCommand (Intent intent, int flags, int startId) {Log. d ("MyService", "onStartCommand executed"); // new Thread (new Runnable () {// @ Override // public void run () {// specific logic // stopSelf ();//}//}). start (); return super. onStartCommand (intent, flags, startId) ;}@ Override public void onDestroy () {Log. d ("MyService", "onDestroy executed"); super. onDestroy ();}}
package com.example.haisun.myapplication3;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.widget.Button;public class MainActivity extends Activity implements View.OnClickListener{      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button start = (Button)findViewById(R.id.start_service);        Button stop = (Button)findViewById(R.id.stop_service);        start.setOnClickListener(this);        stop.setOnClickListener(this);            }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.start_service:                Intent intent = new Intent(this,MyService.class);                startService(intent);                break;            case R.id.stop_service:                Intent stopIntent = new Intent(this,MyService.class);                stopService(stopIntent);                break;                      default:                break;        }    }}

 

 

(2) bind a service through Context. bindService () and unbind it through Context. unbindService.

Here we only add some content in the above example.

1. Create an internal class DownBinder in MyService to inherit the Binder

class DownLoadBinder extends Binder {    public void startDownLoad(){        Log.d("MyService","startDownLoad executed");    }    public int getProgress(){        Log.d("MyService","getProgress executed");        return 0;    }

 

2. Use the onBind method in MyService to return the DownBinder instance for callback after the Activity is successfully bound.

private DownLoadBinder mBinder = new DownLoadBinder();    @Override    public IBinder onBind(Intent intent) {        return mBinder;    }

 

3. Bind in Activity. You need to create a ServiceConnection object to obtain the callback Binder, and then get the DownBinder instance.

private MyService.DownLoadBinder downLoadBinder;    private ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            downLoadBinder = (MyService.DownLoadBinder)service;            downLoadBinder.startDownLoad();            downLoadBinder.getProgress();        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };

4. Similarly, set two buttons to add binding and unbinding click events.

    case R.id.bind_service:                Intent bindIntent = new Intent(this,MyService.class);                bindService(bindIntent,connection,BIND_AUTO_CREATE);                break;    case R.id.unbind_service:                unbindService(connection);                break;

 

 

Lifecycle of Service 3

Matching images officially provided by Google

  

 

Complete Demo address: https://github.com/sunhai1992/ServiceTest

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.