.Net程序员玩转Android开发---(20)Android绑定服务

          绑定服务是在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;
         }
     }

	 
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return 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;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bindservicelayout);
		
		btntime=(Button)findViewById(R.id.btngettime);
		tvtime=(TextView)findViewById(R.id.tvtime);
		
		btntime.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				tvtime.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> 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值