栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android IPC机制ACtivity绑定Service通信代码实例

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android IPC机制ACtivity绑定Service通信代码实例

Binder通信过程类似于TCP/IP服务连接过程binder四大架构Server(服务器),Client(客户端),ServiceManager(DNS)以及Binder驱动(路由器)

其中Server,Client,ServiceManager运行于用户空间,驱动运行于内核空间。这四个角色的关系和互联网类似:Server是服务器,Client是客户终端,SMgr是域名服务器(DNS),驱动是路由器。

book.java

package com.example.android_binder_testservice;

import android.os.Parcel;
import android.os.Parcelable;

public class Book implements Parcelable {
  private String bookName;
  private String author;
  private int publishDate;

  public Book() {

  }

  public Book(String bookName, String author, int publishDate) {
    super();
    this.bookName = bookName;
    this.author = author;
    this.publishDate = publishDate;
  }

  public String getBookName() {
    return bookName;
  }

  public void setBookName(String bookName) {
    this.bookName = bookName;
  }

  public String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public int getPublishDate() {
    return publishDate;
  }

  public void setPublishDate(int publishDate) {
    this.publishDate = publishDate;
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel out, int flags) {
    out.writeString(bookName);
    out.writeString(author);
    out.writeInt(publishDate);
    
  }
  
  
  

  public static final Parcelable.Creator CREATOR = new Creator() {
    @Override
    public Book[] newArray(int size) {
      return new Book[size];
    }


    @Override
    public Book createFromParcel(android.os.Parcel source) {
      return new Book(source);
    }
  };

  public Book(Parcel in) {
    bookName = in.readString();
    author = in.readString();
    publishDate = in.readInt();
  }
}

上面是一个 实现了parcelable的实体类,就是将book序列化,在putExtra到Service时会被写入内存加快程序速度

mainActivity.java

package com.example.android_binder_testservice;

import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
  Button startServiceButton;// 启动服务按钮
  Button shutDownServiceButton;// 关闭服务按钮
  Button startBindServiceButton;// 启动绑定服务按钮
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWidget();
    regiestListener();
  }
  public void getWidget(){
    startServiceButton = (Button) findViewById(R.id.startService);
    startBindServiceButton = (Button) findViewById(R.id.bindService);
    shutDownServiceButton = (Button) findViewById(R.id.stopService);
  }
  public void regiestListener() {
    startServiceButton.setonClickListener(startService);
    shutDownServiceButton.setonClickListener(shutdownService);
    startBindServiceButton.setonClickListener(startBinderService);
  }
  
  public Button.onClickListener startService = new Button.onClickListener() {
    public void onClick(View view) {
      
      Intent intent = new Intent(MainActivity.this,
   CountService.class);
      startService(intent);
      
      Log.v("MainStadyServics", "start Service");
    }
  };
  
  public Button.onClickListener shutdownService = new Button.onClickListener() {
    public void onClick(View view) {
      
      Intent intent = new Intent(MainActivity.this,
   CountService.class);
      
      stopService(intent);
      Log.v("MainStadyServics", "shutDown serveice");
    }
  };
  
  public Button.onClickListener startBinderService = new Button.onClickListener() {
    public void onClick(View view) {
      
      Intent intent = new Intent(MainActivity.this, UseBrider.class);
      startActivity(intent);
      Log.v("MainStadyServics", "start Binder Service");
    }
  };

}

mainActivity中当使用startService()启动Service时会调用Service的onStartCommand()

当使用bindService()则会调用onBind()方法,可能会觉了看的又看怎么没看到bindService()这个方法呢

重点在

Intent intent = new Intent(MainActivity.this, UseBrider.class);
startActivity(intent);

继续上代码

UseBrider.java


public class UseBrider extends FragmentActivity {
  
  CountService countService;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new UseBriderFace(this));

    Intent intent = new Intent(UseBrider.this, CountService.class);
    intent.putExtra("book", new Book("name", "an", 1999));

    
    bindService(intent, conn, Context.BIND_AUTO_CREATE);

  }

  private ServiceConnection conn = new ServiceConnection() {
    
    public void onServiceConnected(ComponentName name, IBinder service) {
      // TODO Auto-generated method stub
      countService = ((CountService.ServiceBinder) service).getService();
      countService.callBack();
    }

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

  };

  protected void onDestroy() {
    super.onDestroy();
    this.unbindService(conn);
    Log.v("MainStadyServics", "out");
  }
}

UseBriderFace.java

public class UseBriderFace extends View{
      
    public UseBriderFace(Context context){
      super(context);
    }
    public void onDraw(Canvas canvas){
      canvas.drawColor(Color.WHITE);//画白色背景
 
      Paint textPaint = new Paint();
      textPaint.setColor(Color.RED);
      textPaint.setTextSize(30);
      canvas.drawText("使用绑定服务", 10, 30, textPaint);
      textPaint.setColor(Color.GREEN);
      textPaint.setTextSize(18);
      canvas.drawText("使用绑定服务后,这个Activity关闭后", 20, 60, textPaint);
      canvas.drawText("绑定的服务也会关闭", 5, 80, textPaint);

    }
  }

UseBriderFace.java类其实就是用java定义的布局可以用xml文件代替

countService.java

package com.example.android_binder_testservice;


import android.app.Service;// 服务的类
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.os.Binder;
import android.content.Intent;
import android.util.Log;


public class CountService extends Service {
  private String TAG = CountService.class.getSimpleName();
  
  boolean threadDisable;
  int count;
  Book book;

  public IBinder onBind(Intent intent) {
    Log.i(TAG, "onBind");
    book = intent.getParcelableExtra("book");
    return new ServiceBinder();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
  }

  @Override
  public boolean onUnbind(Intent intent) {
    Log.i(TAG, "onUnbind");
    return super.onUnbind(intent);
  }

  @Override
  public void onRebind(Intent intent) {
    Log.i(TAG, "onRebind");
    super.onRebind(intent);
  }

  public void onCreate() {
    super.onCreate();
    
    new Thread(new Runnable() {
      public void run() {
 while (!threadDisable) {
   try {
     Thread.sleep(1000);
   } catch (InterruptedException e) {

   }
   count++;
   Log.v("CountService", "Count is" + count);
 }
      }
    }).start();
    Log.i(TAG, "onCreate");
  }

  public void onDestroy() {
    super.onDestroy();
    
    this.threadDisable = true;
    Log.i(TAG, "onDestroy");
  }

  public int getConunt() {
    return count;
  }
  public void callBack(){
    Log.i(TAG, "hello,i am a method of CountService");
  }

  class ServiceBinder extends Binder {
    public CountService getService() {

      return CountService.this;
    }
  }
}

代码解释有了,想不出来了

源码下载地址:http://git.oschina.net/zwh_9527/Binder

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/153807.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号