Android AIDL bindService后不能调用onServiceConnected方法(一种情况)

  1. 像如下代码所示:不能再oncreate()方法在调用service。。

  1. "font-size:18px;">import android.app.Activity;

  2.   import android.content.ComponentName;
  3.   import android.content.Intent;
  4.   import android.content.ServiceConnection;
  5.   import android.os.Bundle;
  6.   import android.os.IBinder;
  7.   import android.os.RemoteException;
  8.   import android.util.Log;
  9.   /**
  10.   * Class Name: SearchClientActivity.java Function:
  11.   *
  12.   * Modifications:
  13.   *
  14.   * @author tm DateTime 2013-1-23 下午4:20:20
  15.   * @version 1.0
  16.   */
  17.   public class SearchClientActivity extends Activity
  18.   {
  19.   private static final String TAG = "SearchClientActivity";
  20.   private ITestService tService = null;
  21.   // 创建远程调用对象
  22.   private ServiceConnection connection = new ServiceConnection( )
  23.   {
  24.   public void onServiceConnected( ComponentName name, IBinder service )
  25.   {
  26.   // TODO Auto-generated method stub
  27.   // 从远程service中获得AIDL实例化对象
  28.   tService = ITestService.Stub.asInterface( service );
  29.   System.out.println( "Bind Success:" + tService );
  30.   }
  31.   public void onServiceDisconnected( ComponentName name )
  32.   {
  33.   // TODO Auto-generated method stub
  34.   tService = null;
  35.   }
  36.   };
  37.   @Override
  38.   protected void onCreate( Bundle savedInstanceState )
  39.   {
  40.   // TODO Auto-generated method stub
  41.   super.onCreate( savedInstanceState );
  42.   setContentView( R.layout.main );
  43.   Intent service = new Intent( ITestService.class.getName( ) );
  44.   // 绑定AIDL
  45.   bindService( service, connection, BIND_AUTO_CREATE );
  46.   //tService为空 死循环等待异步任务结束
  47.   while ( tService == null )
  48.   {
  49.   Thread.sleep( 500 );
  50.   }
  51.   try
  52.   {
  53.   //在客户端调用服务器端的方法
  54.   List< SearchResultItem > resultItems = tService.getSearchResulet( "" 
  55. );
  56.   for ( int i = 0; i < resultItems.size( ); i++ )
  57.   {
  58.   Log.i( TAG, resultItems.get( i ).getIndex( ) + resultItems.get( i 
  59. ).getDetailContent( ) );
  60.   }
  61.   }
  62.   catch ( RemoteException e )
  63.   {
  64.   // TODO Auto-generated catch block
  65.   e.printStackTrace( );
  66.   }
  67.   }
  68.   @Override
  69.   protected void onDestroy( )
  70.   {
  71.   // TODO Auto-generated method stub
  72.   super.onDestroy( );
  73.   unbindService( connection );
  74.   }
  75.   }
复制代码
  结果一直陷入死循环,不跑onServiceConnected方法。

  解决方法:不要在onCreate中等待得到AIDL的接口服务实例,即上面代码中的tService

bindService放在 onCreate中是一个,按照设计思想来说,activty就是要在启动后bind一个service。。(就是调用完oncreate后才会调用bindService)因此,在本例中,不能调用onServiceConnected。可另起一个线程。。或者设置一个按钮手动开始服务。。或者在进入该Activity之前的那个Activity中,开启服务。。。(楼主是用第三种办法解决问问题的)

可参考 http://bbs.9ria.com/thread-232421-1-1.html  

  

你可能感兴趣的:(Android AIDL bindService后不能调用onServiceConnected方法(一种情况))