绑定模式下的Service,service和Activity之间数据的交互

我们目的是在service里面定义一个数据,然后能在Activity下调用和对其数据进行设置。现在我们暂时定义一个最简单的数据int 型的count。

OK,下面先建立一个工程bindservice。

当然Service组件里面最简单的是getset的功能,因此先实现这简单的功能试试。

第一步,先建立一个实现Service组件的功能接口ICountService。

package com.example.bindservice;

public interface ICountService {
      public abstract int getCount();
      public abstract int setCount(int i);
}


 

第二步,毋庸置疑,须建立一个本地绑定的Service类LocalCountService,在里面实现接口。由于是绑定数据,当然得考虑返回绑定的数据类型不能为默认的NULL,所以设置一个自定义的返回的Binder的类,且在此类实现接口。所以可以定为ServiceBinder。由于在绑定模式下,service中的业务逻辑实现得放在onCreate里面。

 

package com.example.bindservice;

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

public class LocalCountService extends Service {
	private boolean threadDisable;
	private int count;
	/**
	 * 自定义的类ServiceBinder用于绑定返回这个类的对象serviceBinder getCount() ---------获得数据
	 * setCount(int i)-----设置数据
	 */
	private ServiceBinder serviceBinder = new ServiceBinder();

	public class ServiceBinder extends Binder implements ICountService {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return count;
		}

		@Override
		public int setCount(int i) {
			// TODO Auto-generated method stub
			count = i;
			return 0;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return serviceBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (!threadDisable) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					count++;
					Log.v("count", "" + getCount());
				}
			}
		}).start();
		// getCount();
		// setCount(3);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return START_STICKY;// 返回此值此则可以保证service一直启动,当然为了在内存不足时候避免被系统清理仍保留的话则需要提高service相应的优先级
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public int getCount() {
		return count;
	}

	public int setCount(int i) {
		// TODO Auto-generated method stub
		this.count = i;
		return 0;
	}
}


第三步,当然是在Activity里面调用查看和修改了。

 

 

package com.example.bindservice;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private ICountService icountService;// 实现方法的接口
	private int VALUE;// 此值用于显示
	TextView txt;
	/***
	 * 以下new ServiceConnection()用于连接绑定服务
	 */
	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			icountService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			icountService = (ICountService) service;
			// LocalcountService.setCount(10086);
			// Toast.makeText(MainActivity.this,
			// ""+LocalcountService.getCount(),Toast.LENGTH_LONG);
			Log.v("count", "" + icountService.getCount());
			// VALUE = LocalcountService.getCount();
		}
	};

	/***
	 * 初始化
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.bindService(
				new Intent("com.example.bindservice.LocalCountService"),
				this.connection, BIND_AUTO_CREATE);// 创建绑定服务
		txt = (TextView) findViewById(R.id.txt);
		txt.setText("" + VALUE);
		Button button = (Button) findViewById(R.id.btn);
		/**
		 * 点击按钮则显示count的值并且重置
		 */
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				VALUE = icountService.getCount();
				Log.v("VALUE", "" + VALUE);
				// Toast.makeText(MainActivity.this, "" + VALUE,
				// Toast.LENGTH_LONG);
				txt.setText("" + VALUE);
				icountService.setCount(10086);
			}
		});

	}

	@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;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		this.unbindService(connection);
		super.onDestroy();
	}

}


当然,最后不要忘记注册Service以及设置其相关属性。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bindservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bindservice.MainActivity"
            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=".LocalCountService">
             <intent-filter>
                 <action android:name="com.example.bindservice.LocalCountService"/>
             </intent-filter>
             </service>
    </application>

</manifest>


另外,附上布局文件

 

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txt" />
    <Button  android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:id="@+id/btn" 
             android:text="查值"
             android:layout_below="@+id/txt"/>

</RelativeLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值