安卓Service组件使用系列4:绑定service并调用service中的方法返回结果

本文介绍如何在安卓应用中绑定Service并调用其方法获取返回结果。通过创建XML布局,设置TextView和Button,实现ServiceConnection,重写onServiceConnected和onServiceDisconnected方法。在MainActivity中绑定和解绑Service,点击按钮时调用Service的方法,将返回数据展示在TextView上。同时定义了一个MyService类,扩展Service,并用LocalBinder暴露service实例和相关方法。

绑定式服务:适合客户端和服务器端数据接口的交互。下面我们以绑定service并调用service中的方法返回结果为背景介绍它的使用方法。

整体思路:在xml文件中放置一个TextView控件、两个Button控件,在MainActivity中实例化一个ServiceConnection类,在这个类中重写onServiceDisconnected和onServiceConnected方法,在onServiceDisconnected方法中设置绑定状态为false,在onServiceConnected方法中获取service实例并设置绑定状态为true;在onStop方法中解除对service的绑定,定义两个Button的点击事件,在一个点击事件中绑定service,在第二个点击事件中调用service的方法获取数据并绑定到TextView控件上。定义一个MyService类,继承Service类,在这个类中定义LocalBinder类,返回service实例,并定义提供给MainActivity调用的方法。

activity_main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:textSize="30sp"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="66dp"
        android:layout_marginTop="33dp"
        android:text="绑定Service服务" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:text="从客户端调用Service的方法" />

</RelativeLayout>
MainActivity.java文件:

package com.example.android_service_binder;
//绑定service的方式      绑定service并调用service的方法返回结果
import com.example.android_service_binder.MyService.LocalBinder;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Button button,button2;
	private TextView textView;
	private MyService myService;
	private boolean mBind=false;//默认是不绑定service的
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button=(Button)findViewById(R.id.button1);
		button2=(Button)findViewById(R.id.button2);
		textView=(TextView)findViewById(R.id.textView1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MainActivity.this,MyService.class);
				bindService(intent, connection, Context.BIND_AUTO_CREATE);
			}
		});
		
//		调用service的方法
		button2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
//				处于绑定的状态
				if(mBind){
					int result=myService.getRandomNum();
					textView.setText("-->"+result);
				}
			}
		});
		
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
//		Intent intent=new Intent(MainActivity.this,MyService.class);
//		bindService(intent, connection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if(mBind){
			unbindService(connection);
			mBind=false;
		}
	}

//	充当着客户端和服务器端的桥梁
	private ServiceConnection connection=new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mBind=false;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			LocalBinder localBinder=(LocalBinder)service;
			myService=localBinder.getService();
			mBind=true;
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
MyService.java文件:

package com.example.android_service_binder;

import java.util.Random;

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

public class MyService extends Service {

	private final Binder binder=new LocalBinder();
	private final Random random=new Random();//产生一个随机数
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return binder;
	}
	
//	返回MyService的实例给客户端调用service中的方法
	public class LocalBinder extends Binder{
		public MyService getService(){
			return MyService.this;
		}
	}
	
//	给客户端(client端)调用的方法       产生随机数
	public int getRandomNum(){
		return random.nextInt(30);
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值