- 像如下代码所示:不能再oncreate()方法在调用service。。
-
“font-size:18px;”>import android.app.Activity;
-
-
import android.content.ComponentName;
-
import android.content.Intent;
-
import android.content.ServiceConnection;
-
import android.os.Bundle;
-
import android.os.IBinder;
-
import android.os.RemoteException;
-
import android.util.Log;
-
/**
-
* Class Name: SearchClientActivity.java Function:
-
*
-
* Modifications:
-
*
-
* @author tm DateTime 2013-1-23 下午4:20:20
-
* @version 1.0
-
*/
-
public class SearchClientActivity extends Activity
-
{
-
private static final String TAG = “SearchClientActivity”;
-
private ITestService tService = null;
-
// 创建远程调用对象
-
private ServiceConnection connection = new ServiceConnection( )
-
{
-
public void onServiceConnected( ComponentName name, IBinder service )
-
{
-
// TODO Auto-generated method stub
-
// 从远程service中获得AIDL实例化对象
-
tService = ITestService.Stub.asInterface( service );
-
System.out.println( “Bind Success:” + tService );
-
}
-
public void onServiceDisconnected( ComponentName name )
-
{
-
// TODO Auto-generated method stub
-
tService = null;
-
}
-
};
-
@Override
-
protected void onCreate( Bundle savedInstanceState )
-
{
-
// TODO Auto-generated method stub
-
super.onCreate( savedInstanceState );
-
setContentView( R.layout.main );
-
Intent service = new Intent( ITestService.class.getName( ) );
-
// 绑定AIDL
-
bindService( service, connection, BIND_AUTO_CREATE );
-
//tService为空 死循环等待异步任务结束
-
while ( tService == null )
-
{
-
Thread.sleep( 500 );
-
}
-
try
-
{
-
//在客户端调用服务器端的方法
-
List< SearchResultItem > resultItems = tService.getSearchResulet( “”
-
);
-
for ( int i = 0; i < resultItems.size( ); i++ )
-
{
-
Log.i( TAG, resultItems.get( i ).getIndex( ) + resultItems.get( i
-
).getDetailContent( ) );
-
}
-
}
-
catch ( RemoteException e )
-
{
-
// TODO Auto-generated catch block
-
e.printStackTrace( );
-
}
-
}
-
@Override
-
protected void onDestroy( )
-
{
-
// TODO Auto-generated method stub
-
super.onDestroy( );
-
unbindService( connection );
-
}
- }
复制代码
结果一直陷入死循环,不跑onServiceConnected方法。
解决方法:不要在onCreate中等待得到AIDL的接口服务实例,即上面代码中的tService
bindService放在 onCreate中是一个,按照设计思想来说
,activty就是要在启动后bind一个service。。(就是调用完oncreate后才会调用bindService)因此,在本例中,不能调用
onServiceConnected。
可另起一个线程。。或者设置一个按钮手动开始服务。。或者在进入该Activity之前的那个Activity中,开启服务。。。(楼主是用第三种办法解决问问题的)
可参考 http://bbs.9ria.com/thread-232421-1-1.html