绑定服务是在android中局部使用的服务,客户端和服务是在同一进程中工作的,不需要跨进程操作。客户端通过bindService方法与服务创建关联

下面这个例子演示客户端调用服务的获取时间方法

1.创建绑定服务

首先创建服务,

服务中创建一个内部类TimeBinder,继承Binder,通过Onbind回调返回服务实例,

在服务中创建一个获取时间的公共方法,供客户端调用

package com.example.helloword;import java.text.SimpleDateFormat;import java.util.Date;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Binder;import android.os.IBinder;public class BindService extends Service {private final IBinder binder= new TimeBinder();//创建一个内部绑定类 public class TimeBinder extends Binder { BindService getService() {             // Return this instance of LocalService so clients can call public methods             return BindService.this;         }     } @Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn binder;} /*只在创建时执行一次*/     @Override     public void onCreate() {         super.onCreate();          }            /*断开绑定或者stopService时执行*/     @Override     public void onDestroy() {        super.onDestroy();            }   /* 当从新尝试绑定时执行 */      @Override    public void onRebind(Intent intent) {         super.onRebind(intent);          }       @Override     public void onStart(Intent intent, int startId) {         super.onStart(intent, startId);            }     @Override      public boolean onUnbind(Intent intent) {            return super.onUnbind(intent);     }   /* ,每次startService都会执行该方法,而改方法执行后会自动执行onStart()方法 */     @Override       public int onStartCommand(Intent intent, int flags, int startId) {                return super.onStartCommand(intent, flags, startId);     }     //获取时间public String getcurtime(){//日期格式 化SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s");Date date = new Date();return format.format(date.getTime());}}

2.调用绑定服务

在客户端,通过bindservice绑定服务

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/btngettime"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="获取时间" />    <TextView        android:id="@+id/tvtime"        android:layout_width="262dp"        android:layout_height="wrap_content"        android:text="TextView" /></LinearLayout>
客户端重写ServiceConnection的两个方法。 onServiceConnected系统调用这个来传递在服务onBind 中返回的IBinder OnServiceDisconnected() 在与系统连接意外丢失,调用这个
package com.example.helloword;import com.example.helloword.BindService.TimeBinder;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.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class BindServiceActivity extends Activity {     private Button btntime;//获取时间private TextView tvtime;//显示时间BindService bindservice;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.bindservicelayout);btntime=(Button)findViewById(R.id.btngettime);tvtime=(TextView)findViewById(R.id.tvtime);btntime.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubtvtime.setText(bindservice.getcurtime());}});}@Override    protected void onStart() {        super.onStart();        // Bind to LocalService        Intent intent = new Intent(this, BindService.class);        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);    }private ServiceConnection mConnection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName className,                IBinder service) {            // We've bound to LocalService, cast the IBinder and get LocalService instance           TimeBinder binder = (TimeBinder)service;        bindservice=binder.getService();                  }        @Override        public void onServiceDisconnected(ComponentName arg0) {        bindservice=null;        }    };    }


androidmanifest.xml

  <activity android:name="com.example.helloword.BindServiceActivity">             <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                                <service   android:name=".BindService">     <intent-filter>          <action android:name="com.example.helloword.BindService" />          <category android:name="android.intent.category.default" />    </intent-filter>  </service> 



更多相关文章

  1. tcping测试服务器TCP端口
  2. Android(安卓)ViewRootImpl 解析
  3. Android(安卓)Studio Mac常用快捷键
  4. js判断移动端是否安装某款app的多种方法
  5. android Service相关知识点
  6. Android数据存储之三SQLite嵌入式数据库(1)
  7. Android之通过HTTP协议向服务器发送XML数据
  8. Android中的OnMeasure及OnLayout
  9. Android(安卓)窗口添加机制系列1-Activity

随机推荐

  1. Android(安卓)开发注意事项
  2. android4.0编译错误集(一)
  3. Android友盟统计和埋点
  4. 跟我学 Saltstack 常用模块及 API
  5. Android(安卓)RelativeLayout布局
  6. Android中Spinner下拉列表(使用ArrayAdapt
  7. Android(安卓)简单存储 SharedPreference
  8. Android与JS交互之基本
  9. 使用MediaPlayer播放声音的异常
  10. android onSaveInstanceState方法