zoukankan      html  css  js  c++  java
  • android学习-IPC机制之ACtivity绑定Service通信

    bindService获得Service的binder对象对服务进行操作

     

    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<Book> CREATOR = new Creator<Book>() {
            @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();
        }
    }
    View Code

    上面是一个 实现了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);
                /** 退出Activity是,停止服务 */
                stopService(intent);
                Log.v("MainStadyServics", "shutDown serveice");
            }
        };
        /** 打开绑定服务的Activity */
        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");
            }
        };
    
    }
    View Code

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

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

    重点在

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

    继续上代码

    UseBrider.java

     1 /** 通过bindService和unBindSerivce的方式启动和结束服务 */
     2 public class UseBrider extends FragmentActivity {
     3     /** 参数设置 */
     4     CountService countService;
     5 
     6     @Override
     7     public void onCreate(Bundle savedInstanceState) {
     8         super.onCreate(savedInstanceState);
     9         setContentView(new UseBriderFace(this));
    10 
    11         Intent intent = new Intent(UseBrider.this, CountService.class);
    12         intent.putExtra("book", new Book("name", "an", 1999));
    13 
    14     /** 进入Activity开始服务
    15 
    16      * conn
    17      */
    18         bindService(intent, conn, Context.BIND_AUTO_CREATE);
    19 
    20     }
    21 
    22     private ServiceConnection conn = new ServiceConnection() {
    23         /*
    24          * 这个方法会获取到CountService的onBind方法中返回的Binder对象
    25          * 然后就可以对服务进行某种操作了
    26          */
    27         public void onServiceConnected(ComponentName name, IBinder service) {
    28             // TODO Auto-generated method stub
    29             countService = ((CountService.ServiceBinder) service).getService();
    30             countService.callBack();
    31         }
    32 
    33         /** 无法获取到服务对象时的操作 */
    34         public void onServiceDisconnected(ComponentName name) {
    35             // TODO Auto-generated method stub
    36             countService = null;
    37         }
    38 
    39     };
    40 
    41     protected void onDestroy() {
    42         super.onDestroy();
    43         this.unbindService(conn);
    44         Log.v("MainStadyServics", "out");
    45     }
    46 }
    View Code

    UseBriderFace.java

     1 public class UseBriderFace extends View{
     2             /**创建参数*/
     3         public UseBriderFace(Context context){
     4             super(context);
     5         }
     6         public void onDraw(Canvas canvas){
     7             canvas.drawColor(Color.WHITE);//画白色背景
     8                 /**绘制文字*/
     9             Paint textPaint = new Paint();
    10             textPaint.setColor(Color.RED);
    11             textPaint.setTextSize(30);
    12             canvas.drawText("使用绑定服务", 10, 30, textPaint);
    13             textPaint.setColor(Color.GREEN);
    14             textPaint.setTextSize(18);
    15             canvas.drawText("使用绑定服务后,这个Activity关闭后", 20, 60, textPaint);
    16             canvas.drawText("绑定的服务也会关闭", 5, 80, textPaint);
    17             
    18         }
    19     }
    View Code

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

    countService.java

     1 package com.example.android_binder_testservice;
     2 
     3 /**引入包*/
     4 import android.app.Service;// 服务的类
     5 import android.os.IBinder;
     6 import android.os.Parcel;
     7 import android.os.RemoteException;
     8 import android.os.Binder;
     9 import android.content.Intent;
    10 import android.util.Log;
    11 
    12 /** 计数的服务 */
    13 public class CountService extends Service {
    14     private String TAG = CountService.class.getSimpleName();
    15     /** 创建参数 */
    16     boolean threadDisable;
    17     int count;
    18     Book book;
    19 /*
    20  * 当通过bindService()启动CountService时会调用这个方法并返回一个ServiceBinder对象
    21  * 这个Binder对象封装着一个CountService实例,
    22  * 客户端就可以通过ServiceBinder对服务端进行一些操作
    23  */
    24     public IBinder onBind(Intent intent) {
    25         Log.i(TAG, "onBind");
    26         book = intent.getParcelableExtra("book");
    27         return new ServiceBinder();
    28     }
    29 
    30     @Override
    31     public int onStartCommand(Intent intent, int flags, int startId) {
    32         Log.i(TAG, "onStartCommand");
    33         return super.onStartCommand(intent, flags, startId);
    34     }
    35 
    36     @Override
    37     public boolean onUnbind(Intent intent) {
    38         Log.i(TAG, "onUnbind");
    39         return super.onUnbind(intent);
    40     }
    41 
    42     @Override
    43     public void onRebind(Intent intent) {
    44         Log.i(TAG, "onRebind");
    45         super.onRebind(intent);
    46     }
    47 
    48     public void onCreate() {
    49         super.onCreate();
    50         /** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */
    51         new Thread(new Runnable() {
    52             public void run() {
    53                 while (!threadDisable) {
    54                     try {
    55                         Thread.sleep(1000);
    56                     } catch (InterruptedException e) {
    57 
    58                     }
    59                     count++;
    60                     Log.v("CountService", "Count is" + count);
    61                 }
    62             }
    63         }).start();
    64         Log.i(TAG, "onCreate");
    65     }
    66 
    67     public void onDestroy() {
    68         super.onDestroy();
    69         /** 服务停止时,终止计数进程 */
    70         this.threadDisable = true;
    71         Log.i(TAG, "onDestroy");
    72     }
    73 
    74     public int getConunt() {
    75         return count;
    76     }
    77     public void callBack(){
    78         Log.i(TAG, "hello,i am a method of CountService");
    79     }
    80 
    81     class ServiceBinder extends Binder {
    82         public CountService getService() {
    83 
    84             return CountService.this;
    85         }
    86 
    87     }
    88 }
    View Code

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

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

  • 相关阅读:
    Ubuntu包管理命令 dpkg、apt和aptitude
    Linux curses库使用
    VC皮肤库SkinSharp 1.0.6.6的使用
    HOG(方向梯度直方图)
    2014年国外发布的中国内地大学排名18强名单
    sql语句中BEGIN TRAN...COMMIT TRAN
    搜索框中“请输入搜索keyword”
    IOS基于新浪微博开放平台微博APP
    php字符串标点等字符截取不乱吗 封装方法
    谈一谈struts2和springmvc的拦截器
  • 原文地址:https://www.cnblogs.com/gne-hwz/p/6636744.html
Copyright © 2011-2022 走看看