远程服务没有绑定/ asInterface返回“null”

时间:2011-09-22 17:16:50

标签: android service bind

我在this一书中的示例之后创建了一个远程服务,并尝试将其与此活动绑定:

public class TuCanMobileActivity extends Activity {
/** Called when the activity is first created. */
//private HTTPSbrowser mBrowserService;
private HTTPBrowserRemote mBrowserRemoteService;
private Boolean mbound=false;
private ServiceConnection mBrowserRemoteServiceConnection = 
    new ServiceConnection() {           
        @Override
        public void onServiceDisconnected(ComponentName name) {
            try {
                mBrowserRemoteService.unregister_course_callback(courseCallback);
            } catch (RemoteException e) {}
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBrowserRemoteService=HTTPBrowserRemote.Stub.asInterface(service);
            mbound=true;
            try {
                mBrowserRemoteService.register_course_callback(courseCallback);

            }
            catch (RemoteException e) {
                // TODO: handle exception
            }
        }

};

private final IClassesCallback courseCallback =
    new IClassesCallback.Stub() {
        @Override
        public void expressClassesdata(HTTPSResponse ClassesResponse)
                throws RemoteException {
            Toast.makeText(TuCanMobileActivity.this, "Just works??", Toast.LENGTH_SHORT).show();

            final TextView txtLoginName = 
                (TextView) findViewById(R.id.textView1);
            txtLoginName.setText(ClassesResponse.HTMLResponse);
        }
    };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
public void onClickSendLogin (final View sfNormal) {
    final Intent browserIntent = new Intent(TuCanMobileActivity.this,HTTPBrowserRemoteImpl.class);

    this.bindService(browserIntent, mBrowserRemoteServiceConnection, Context.BIND_AUTO_CREATE);
    if(mbound==true){
        Toast.makeText(TuCanMobileActivity.this, "Service Bound", Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(TuCanMobileActivity.this, "Service NOT Bound", Toast.LENGTH_SHORT).show();
    }
    try {

        mBrowserRemoteService.call_course_overview();


    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    /*final Intent i = new Intent(this,MainMenu.class);
    startActivity(i);*/
    unbindService(mBrowserRemoteServiceConnection);
}
}

但是mBrowsserRemoteService为null(在onClickSendLogin方法中)并返回NullPointerException,我不知道为什么?似乎从不调用服务中的onBind方法。我的问题在哪里。

提前致谢 Tyde

1 个答案:

答案 0 :(得分:2)

您获得NullPointerException的原因是因为您正在执行

mBrowserRemoteService.call_course_overview();

无论mbound如何; mbound在那时可能是真或假。

我怀疑更大的问题是您无法绑定到此服务,因为您的AndroidManifest.xml配置不正确。如果您仍然遇到问题,请发布您的AndroidManifest文件。