一、把输入文本的数据同步到服务的实例(如何执行服务的内部代码)

  绑定服务比启动服务更加方便高效,绑定服务中的直接方法调用比Intent作为载体传输更为快捷得多。

1、activity_main.xml

  <Button
    android:text="绑定服务"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnBindService" />
  <Button
    android:text="解除绑定服务"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnUnbindService" />
  <Button
    android:text="同步数据"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnSyncData" />

2、MainActivity.java

  private MyService.Binder binder = null;

  findViewById(R.id.btnBindService).setOnClickListener(this);
  findViewById(R.id.btnUnbindService).setOnClickListener(this);
  findViewById(R.id.btnSyncData).setOnClickListener(this);

  case R.id.btnBindService:
    bindService(new Intent(this,MyService.class),this,Context.BIND_AUTO_CREATE);
    break;
  case R.id.btnUnbindService:
    unbindService(this);
  break;
  case R.id.btnSyncData:
    if (binder != null) {
      binder.setData(editText.getText().toString());
    }
  break;

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
    binder = (MyService.Binder)service;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {  }

3、MyService.java

  public IBinder onBind(Intent intent) {
    return new Binder();
  }

  public class Binder extends android.os.Binder{
    public void setData(String data){
      MyService.this.data = data;

    }
  }

二、内部信息呈现到外界的实例(如何侦听服务的内部状态)

1、activity_main.xml

  <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvOut"/>

2、MainActivity.java

  private TextView textView;

  textView = (TextView) findViewById(R.id.tvOut);

  public void onServiceConnected(ComponentName name, IBinder service) {
    binder = (MyService.Binder)service;
    binder.getService().setCallback(new MyService.Callback(){
      @Override
      public void onDataChange(String data) {
        //textView.setText(data);  //错误用法。程序由新创建的线程调用,不允许其他辅线程来直接获取UI线程(主线程)的资源。
        Message msg = new Message();
        Bundle b = new Bundle();
        b.putString("data",data);
        msg.setData(b);
        handler.sendMessage(msg);
      }
    });
  }

  private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      textView.setText(msg.getData().getString("data"));
    }
  };

3、MyService.java

  public class Binder extends android.os.Binder{
    public void setData(String data){
      MyService.this.data = data;
    }
    public MyService getService(){
      return MyService.this;
    }
  }

  public void onCreate() {
    super.onCreate();
    running = true;
    new Thread(){
    @Override
    public void run() {
      super.run();
      int i = 0 ;
      while(running){
        i++;
        String str = i+":"+data;
        System.out.println(str);
        if(callback != null){
          callback.onDataChange(str);
        }
         try {
            sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }.start();
  }

  private Callback callback = null;

  public void setCallback(Callback callback) {
    this.callback = callback;
  }
  public Callback getCallback() {
    return callback;
  }
  //内部通知外界:回调机制
  public static interface Callback{
    void onDataChange(String data);
  }

Android中Service通信(二)——绑定Service进行通信的更多相关文章

  1. Android中startService的使用及Service生命周期

    Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法.本文仅仅探讨纯startService的使用.不 ...

  2. Android WiFiDirect 学习(二)——Service Discovery

    Service Discovery 简介 在Android WifiDirect学习(一 )中,简单介绍了如何使用WifiDirect进行搜索——连接——传输. 这样会有一个问题,那就是你会搜索到到附 ...

  3. Android中使用"running services"查看service进程内存

    从Android 2.0开始,在Settings中加入了一个新的activity("Running Services" activity),它用于显示当前运行的每个Services ...

  4. (原)android中的动画(二)

    帧动画的使用需要在xml文件中指定每一帧所对应的图片 animation-list写法如下: <?xml version="1.0" encoding="utf-8 ...

  5. Android学习笔记(八)深入分析Service启动、绑定过程

    Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...

  6. Tabhost中Activity绑定Service

    在android中,一个Activity绑定一个Service组件我们一般用Context().bindService方法就能够.可是假设这个 Activity属于一个Tabhost的话就不行了,在网 ...

  7. Android中Service概述

    Service是Android中一种非常重要的组件,一般来说有两种用途:用Service执行长期执行的操作,而且与用户没有UI界面的交互:某个应用程序的Service能够被其它应用程序的组件调用以便提 ...

  8. 深入分析Service启动、绑定过程

    Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...

  9. Android中如何查看内存

    文章参照自:http://stackoverflow.com/questions/2298208/how-to-discover-memory-usage-of-my-application-in-a ...

随机推荐

  1. Centos 6.5 Percona 5.6.27 Tokudb 配置

    参考 https://www.percona.com/doc/percona-server/5.6/tokudb/tokudb_installation.html # wget https://www ...

  2. Windows Server 2012 虚拟化实战:网络(一)

    虚拟化对于计算的抽象,大家可能相对熟悉,也许都有在单机使用诸如Virtual PC或者Virtual Box的经验.使用的这些虚拟化软件的第一印象就是我们的CPU可以同时运行多套不同的操作系统,并且其 ...

  3. linux共享windows文件并自动化改变文件编码

    以k3日志为例: 在k3的数据库服务器进行如下操作: 1.在k3的数据库服务器导出日志数据到本地D:/K3LOG下(脚本自动化执行) 2.设置脚本定时任务每天拷贝D:/K3LOG下的文件到D:/K3L ...

  4. 字符串编辑距离(Levenshtein距离)算法

    基本介绍 Levenshtein距离是一种计算两个字符串间的差异程度的字符串度量(string metric).我们可以认为Levenshtein距离就是从一个字符串修改到另一个字符串时,其中编辑单个 ...

  5. Webform:Application、ViewState对象的用法

    Application Application对象的作用范围是整个全局,也就是说对所有用户都有效.它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所以可以在不同页面中对它进行存取.它和S ...

  6. CodeAtlas For Sublime Text

    CodeAtlas is a plugin of SublimeText, which allows one to explore the call graph conveniently. The p ...

  7. 安全测试 - 抓包工具BurpSuite

    Brup SuiteBurpSuite是用于攻击web应用程序的集成平台.它包含了许多工具,并为这些工具设计了许多接口,以促进加快攻击应用程序的过程.所有的工具都共享一个能处理并显示HTTP消息,持久 ...

  8. [LeetCode] Longest Palindromic Substring 最长回文串

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  9. Anna-senpai帖子翻译与Mirai源代码使用

    Anna-senpai这个人太好玩了,整件事就像没有黄段子的无聊世界那样. 无聊翻译了一下,顺便实验了效果. --------------------------------------------- ...

  10. 安装Anaconda

    安装Anaconda来安装一切 spyder是python科学计算IDE,类似matlab.这是一个基于Qt的软件,如果使用pip install安装,会出现各种bug.pip install spy ...