zoukankan      html  css  js  c++  java
  • BindService总结

    一、整体工程图



    二、activity_bind.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical">
    
    
    <Button android:text="useService" 
        android:id="@+id/buttonUseService" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"></Button>
    </LinearLayout>
    


    三、BindActivity.java

    package com.jltxgcy.bindservice;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Toast;
    
    import com.jltxgcy.bindservice.LocalService.LocalBinder;
    
    public class BindActivity extends Activity {
    
    	LocalService mService;
        boolean mBound = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_bind);
            findViewById(R.id.buttonUseService).setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				if (mBound) {
    		            // Call a method from the LocalService.
    		            // However, if this call were something that might hang, then this request should
    		            // occur in a separate thread to avoid slowing down the activity performance.
    		            int num = mService.getRandomNumber();
    		            Toast.makeText(BindActivity.this, "number: " + num, Toast.LENGTH_SHORT).show();
    		        }
    				
    			}
    		});
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            // Bind to LocalService
            Intent intent = new Intent(this, LocalService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
        }
        
    
        /** Defines callbacks for service binding, passed to bindService() */
        private ServiceConnection mConnection = new ServiceConnection() {
    
            @Override
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                // We've bound to LocalService, cast the IBinder and get LocalService instance
                LocalBinder binder = (LocalBinder) service;
                mService = binder.getService();
                mBound = true;
                Log.d("jltxgcy", "onServiceConnected");
            }
    
            //Called when the connection with the service disconnects unexpectedly
            @Override
            public void onServiceDisconnected(ComponentName arg0) {
                mBound = false;
                Log.d("jltxgcy", "onServiceDisconnected");
            }
        };
    }


    四、LocalService.java

    package com.jltxgcy.bindservice;
    
    import java.util.Random;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;
    
    public class LocalService extends Service {
    	public static final String TAG="jltxgcy";
    	 // Binder given to clients
        private final IBinder mBinder = new LocalBinder();
        // Random number generator
        private final Random mGenerator = new Random();
        
    
        @Override
    	public void onCreate() {
        	Log.d(TAG, "onCreate");
    		super.onCreate();
    	}
        
    	/**
         * Class used for the client Binder.  Because we know this service always
         * runs in the same process as its clients, we don't need to deal with IPC.
         */
        public class LocalBinder extends Binder {
            LocalService getService() {
                // Return this instance of LocalService so clients can call public methods
                return LocalService.this;
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
        	Log.d(TAG, "onBind");
            return mBinder;
        }
    
        /** method for clients */
        public int getRandomNumber() {
          return mGenerator.nextInt(100);
        }
    
    	@Override
    	public boolean onUnbind(Intent intent) {
    		Log.d(TAG, "onUnbind");
    		return super.onUnbind(intent);
    	}
    
    	@Override
    	public void onDestroy() {
    		Log.d(TAG, "onDestroy");
    	
    	}
    }


    五、详解

            程序开始,绑定Service,结果显示如下:

             

            说明了调用的先后顺序。onBind方法得到了IBinder对象,onServiceConnected方法将IBinder对象向下转型为LocalBinder对象,通过调用getService取得Service实例, 这样就可以在BindActivity中使用Service的方法。

            按Back键退出,调用

            


  • 相关阅读:
    梅森素数
    高精度乘法
    快速幂取模
    高精度加法
    Linux 压缩&解压缩
    Lec_Cloud资源云平台
    IP102,IP102-K_V3.0 输入节点机
    A7互动主机
    音频处理器的使用
    关于测试随笔
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3281384.html
Copyright © 2011-2022 走看看