在Android里,Service的数据绑定是一种重要的用法,我们知道Service与Activity一样是运行在当前应用进程的主线程里面的,他们之间交互的方式有多种,下面我来介绍一下如何使用数据绑定的方法通过Service向Activity交互数据


1.首先我们要定义一个接口,接口里定义我们需要实现的方法

public interface ICount {public int getcount();}

2.接下来我们需要一个Service的子类实现本接口,定义一个ServiceBinder的内部类,通过它的对象来绑定数据,要注意的是我们如果要进行耗时操作的话,仍然需要在Service中创建线程,Service自身就是运行在主线程中的。还有一个就是OnBind的返回值是IBinder,但是这里我使用ServiceBinder对象是继承Binder的,那为什么这里可以这么写呢?因为Binder是Base class for a remotable object, the core part of a lightweight remote procedure call mechanism defined byIBinder,是直接从IBinder这里的直接子类

public class BackGroundService extends Service implements ICount {private boolean disable;  //线程是否执行的标识位private int count;      //计数private ServiceBinder serviceBinder = new ServiceBinder();public class ServiceBinder extends Binder implements ICount {@Overridepublic int getcount() {// TODO Auto-generated method stubreturn 0;}}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn serviceBinder;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();new Thread(new Runnable() {// @Overridepublic void run() {while (!disable) {try {Thread.sleep(1000);} catch (InterruptedException e) {}count++;System.out.println("CountService Count is " + count);}}}).start();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubreturn super.onStartCommand(intent, flags, startId);}@Overridepublic int getcount() {return count;// TODO Auto-generated method stub}@Overridepublic void onDestroy() {// TODO Auto-generated method stubthis.disable = true;//Log.v(" CountService ", " on destroy ");System.out.println("Service destroy...");super.onDestroy();}}


3.定义完了Service这一部分的内容,接下来就需要在AndroidManifest.xml中注册了,需要注意的是这里不仅要对我们包类的Service进行声明,同时还需要声明intent的过滤器

        <service android:name="com.yqc.testservice.BackGroundService">            <intent-filter>                <action android:name="com.yqc.testservice.BackGroundService" />            </intent-filter>        </service>


4.定义完毕以后,接下来需要在Activity中的交互部分了,刚才在配置文件中定义的Intent的过滤器这里就用到了,在bindService方法中,这就是他的一个参数,然后通过ServiceConnetion的对象与Service建立连接并取得后台的参数。

public class MainActivity extends Activity {Button btn_start;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);this.bindService(new Intent("com.yqc.testservice.BackGroundService"),this.serviceConnection, BIND_AUTO_CREATE);btn_start = (Button) findViewById(R.id.btn_start);btn_start.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub}});}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubthis.unbindService(serviceConnection);System.out.println("Activity Destroy...");super.onDestroy();}private ICount countentity;private ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubcountentity = (ICount) service;System.out.println(" CountService on serivce connected, count is "+ countentity.getcount());}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubcountentity = null;}};}

5.最后得到的结果如下





更多相关文章

  1. Android(安卓)Studio自定义模板 写页面竟然可以如此轻松
  2. Android(安卓)进程间通信的几种实现方式
  3. android中将复杂json对象进行数据转换
  4. Android的AIDL服务
  5. Flutter 与原生交互总结
  6. adapter用法
  7. Android自定义动画专题一
  8. android中actionBar中字体颜色设置
  9. AndroidStudio使用GreenDao实战

随机推荐

  1. Android预安装软件&adb命令&编译源码
  2. Android 分析:Process xxxxx (pid 30262)
  3. 【Android-UnitTest】Android单元测试问
  4. android驱动学习-led次设备号(2)
  5. Android 准确过滤(禁止) Emoji表情
  6. android 横纵屏切换
  7. android 已省内存方式把图片加载到内存
  8. android的Menu使用
  9. Android NDK r8 windows环境搭建
  10. 从J2EE转向Android的第八天-----Toast