android bindservice

前端之家收集整理的这篇文章主要介绍了android bindservice前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试绑定到已经启动的服务时,我在行mService.start()处获得空指针异常.我从不同的活动(服​​务开始的地方)做同样的事情,everythig正确.所有这些活动都是一个应用程序的一部分

你觉得我做错了什么?

public class RouteOnMap extends MapActivity{
    private static final int NEW_LOCATION = 1;
    private static final int GPS_OFF = 2;

    private MapView mMapView;
    private ILocService mService;
    private boolean mServiceStarted;
    private boolean mBound;
    private Intent mServiceIntent;
    private double mLatitude,mLongitude;

    private ServiceConnection connection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,IBinder iservice) {
            mService = ILocService.Stub.asInterface(iservice);
            mBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            mService = null;
            mBound = false;
        }

    };

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);

        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setBuiltInZoomControls(true);      
        mServiceIntent = new Intent();
        mLatitude = 0.0;
        mLongitude = 0.0;
        mBound = false;
    }

    @Override
    public void onStart(){
        super.onStart();

        mServiceIntent.setClass(this,LocationService.class);
        //startService(mServiceIntent);
        if(!mBound){
            mBound = true;
            this.bindService(mServiceIntent,connection,Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    public void onResume(){
        super.onResume();


        try {
            mService.start();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause(){
        super.onPause();

        if(mBound){
            this.unbindService(connection);
        }
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

}

解决方法

您无法知道服务是否受onResume()约束. bindService()不是阻塞调用.从onServiceConnected()方法调用mService.start().

猜你在找的Android相关文章