2.App Components-Services/Bound Services

1. Bound Services

  A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send

    requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves

    another application component and does not run in the background indefinitely

2. The Basics

  A bound service is an implementation of the Services class that allows other applications to bind to it and interact with it. To provide binding

    for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming

    interface that clients can use to interact with the service.

3. Creating a Bound Service

  When creating a service that provides binding, you must provide an IBinder that provides the programming interface that clients can use to

    interact with the service. There are three ways you can define the interface:

    <1>Extending the Binder class

    <2>Using a Messenger

    <3>Using AIDL

4. Extending the Binder class

  If your service is private to your own application and runs in the same process as the client (which is common), you should create your

    interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to

    directly access public methods available in either the Binder implementation or even the Service.

  This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not

    create your interface this way is because your service is used by other applications or across separate processes.

//activity_bingding.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mirror.android.extendingbinder.BindingActivity" >
    <Button
        android:id = "@+id/btn_create_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create service" />
</RelativeLayout>
//LocalService.class
package mirror.android.extendingbinder;

import java.util.Random;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class LocalService extends Service {    

    private final IBinder mBinder = new LocalBinder();
    private final Random mGenerator = new Random();

    /*1.In your service, create an instance of Binder that either:
     *     <1> contains public methods that the client can call
     *  <2> returns the current Service instance, which has public methods the client can call
     *  <3> or, returns an instance of another class hosted by the service with public methods the client can call
    */
    public class LocalBinder extends Binder{
        LocalService getService(){
            return LocalService.this;
        }
    }

    /*2.Return this instance of Binder from the onBind() callback method.
    */
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }

    /*The LocalBinder provides the getService() method for clients to retrieve the current instance of LocalService.
     *This allows clients to call public methods in the service.
     *For example, clients can call getRandomNumber() from the service.*/
    public int getRandomNumber(){
        return mGenerator.nextInt();
    }
}
//BindingActivity.class
package mirror.android.extendingbinder;

import mirror.android.extendingbinder.LocalService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class BindingActivity extends Activity {

    private Button button;

    LocalService mService;
    Boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binding);

        button = (Button)findViewById(R.id.btn_create_service);
        ButtonListener buttonListener = new ButtonListener();
        button.setOnClickListener(buttonListener);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //1.bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //2.unbind from service
        if(mBound){
            unbindService(mConnection);
            mBound = false;
        }
    }

    class ButtonListener implements OnClickListener{
        //3.Call a method from the LocalService.
        //create a separate thread if needed;
        @Override
        public void onClick(View v) {
            if(mBound){
                int num = mService.getRandomNumber();
                Toast.makeText(getApplicationContext(), "number: " + num, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        //3.In the client, receive the Binder from the onServiceConnected() callback method
        //  and make calls to the bound service using the methods provided.
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocalBinder binder = (LocalBinder)service;
            mService = binder.getService();
            mBound = true;
        }
    };
}
//manifest.xml
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".BindingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".LocalService"></service>
    </application>

  

5. Using a Messenger

  If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service.

    This technique allows you to perform interprocess communication (IPC) without the need to use AIDL.

时间: 2024-11-08 18:26:22

2.App Components-Services/Bound Services的相关文章

API翻译 --- Bound Services

目录: 1.The Basics 最基本的 2.Declaring a service in the manifest 在服务清单中配置 3.Creating a Started Service Extending the IntentService class 创建一个服务扩展类 4.Extending the Service class 继承Serrvice类 5.Starting a service 开始服务 6.Stopping a service 结束服务 7.Creating a B

unable to apply changes:plugins &quot;App links assistant&quot;,firebase services won&#39;

新安装的android studio工具报错,本来以为只要在plugins中安装android support插件的,现在点击该插件还是不能apply,提示: unable to apply changes:plugins "App links assistant",firebase services won' 解决办法: 只要把红色的plugin 取消勾选即可,再点击android support apply就可以 unable to apply changes:plugins &q

Android官方文档之Bound Services

绑定式Service在CS结构中扮演着Server的角色.绑定式Service允许其他组件(如Activity)绑定该Service.发送请求.接收响应.甚至IPC通信( interprocess communication).绑定式Service通常服务于其他应用程序的组件.且没有明确的后台的概念(does not run in the background indefinitely). 本文将介绍bound Service的相关内容,包括其创建.与其他应用组件如何绑定 等.有关Service

Android Studio中的App Components重要点记述

阅读英文文档而理解的file:///E:/Android2016/sdk/docs/guide/components/fundamentals.html#Components App Compnents 每个component都是系统可以进入你的app的一种方式,但是不是所有的component都是对于user而言的真实的entry points. 共有四种app components: Activity: 每一个activity代表用户界面的一个单独的屏幕,这些activity是相互独立的 S

Android官方文档之App Components(Activities)

Activity是Android四大组件之首,本文将介绍Activity的含义.创建.启动.销毁.生命周期 等. 如需访问官方原文,您可以点击这个链接:<Activities> Activities Activity是一个类,它是Android呈现界面的载体,用于与用户操作交互,如拨号.照相.发送邮件.展示地图 等.每个Activity都承载了一个Window,这个Window用来绘制UI(User Interface).一般情况下,该Window铺满(fill)整个屏幕:有时候,它也可以悬浮

Android官方文档之App Components(Common Intents)

Intent的真正强大之处在于它的隐式Intent,隐式Intent需要配合Intent-filters使用,有关这方面的概念和知识,您可以参考我翻译的官方文档:<Android官方文档之App Components(Intents and Intent Filters)>. 隐式Intent足够强大,以至于系统提供了大量的Intent方便开发者启动系统应用程序,本文将介绍一些常用的隐式Intent.以及如何自定义intent-filters以匹配隐式intent. 如需阅读官方原文,您可以点

Android官方文档之App Components(Intents and Intent Filters)

Android应用框架鼓励开发者在开发应用时重用组件,本文将阐述如何用组件构建应用程序以及如何用intent将组件联系起来. 如需阅读官方原文,请您点击这个链接: <App Components>. 您还可以参考这些博文: <Using DialogFragments> <Fragments For All> <Multithreading For Performance> 以及这些Training: <Managing the Activity Li

5、二、App Components(应用程序组件):0、概述

二.App Components(应用程序组件) 0.概述 ? App Components Android's application framework lets you create rich and innovative apps using a set of reusable components. This section explains how you can build the components that define the building blocks of your

Android官方文档之App Components(Common Intents)(转载)

原文地址:http://blog.csdn.net/vanpersie_9987/article/details/51244558#rd Intent的真正强大之处在于它的隐式Intent,隐式Intent需要配合Intent-filters使用,有关这方面的概念和知识,您可以参考我翻译的官方文档:<Android官方文档之App Components(Intents and Intent Filters)>. 隐式Intent足够强大,以至于系统提供了大量的Intent方便开发者启动系统应用