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

  绑定服务比启动服务更加方便高效,绑定服务中的直接方法调用比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. 用Retrofit发送请求中添加身份验证

    用Retrofit发送请求中添加身份验证====================在安卓应用开发中, retrofit可以极大的方便发送http网络请求,不管是GET, POST, 还是PUT, DEL ...

  2. IO流中将字节流转成字符流的方法

    //字节流--->字符流 1. public class TestIO { public static void main(String[] args) throws IOException { ...

  3. Intellij IDEA 快捷键整理

    CSDN 2016博客之星评选结果公布      [系列直播]算法与游戏实战技术      "我的2016"主题征文活动 Intellij IDEA 快捷键整理(TonyCody) ...

  4. jdbc java数据库连接 8)防止sql注入

    回顾下之前jdbc的开发步骤: 1:建项目,引入数据库驱动包 2:加载驱动 Class.forName(..); 3:获取连接对象 4:创建执行sql语句的stmt对象;  写sql 5:执行sql ...

  5. kubernetes单机板

    参考地址: *** http://blog.csdn.net/carter115/article/details/51121223 ** http://www.cnblogs.com/dongdong ...

  6. coocs2d-x 分辨率

    config.lua: CC_DESIGN_RESOLUTION = { width = , height = , autoscale = "FIXED_HEIGHT", call ...

  7. Android基础总结(六)

    创建第二个Activity(掌握) 需要在清单文件中为其配置一个activity标签 标签中如果带有这个子节点,则会在系统中多创建一个快捷图标 <intent-filter> <ac ...

  8. js判断浏览器类型

    使用navigator.userAgent和来判断 PC端: <script type="text/javascript">var ua=navigator.userA ...

  9. jquery的几种ajax提交方式

    $.post( url, function(data){ if(data.retcode == "0"){ alert(data.retmsg); }else{ alert(dat ...

  10. LAMP(1) 在VirtualBox里安装Ubuntu Server

    问题0.虚拟机中安装lamp环境 问题解决: 来自百度经验 问题1. 用putty远程登陆linux系统,显示network error connection refused 问题解决 问题2. my ...