1. 程式人生 > >Android AIDL bindService後不能呼叫onServiceConnected方法(一種情況)

Android AIDL bindService後不能呼叫onServiceConnected方法(一種情況)

  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.   }