【问题标题】:android bindservice安卓绑定服务
【发布时间】:2010-05-15 23:24:57
【问题描述】:

当我尝试绑定到已启动的服务时,在 mService.start() 行出现空指针异常。我从不同的活动(服​​务开始的地方)做同样的事情,一切都很顺利。所有这些活动都是一个应用程序的一部分。

你认为我做错了什么?

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

}

【问题讨论】:

    标签: android service


    【解决方案1】:

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

    【讨论】:

    • 谢谢。从 onServiceConnected 调用 mService.start() 有效。您是否建议始终从 onServiceConnected() 调用 mService 方法?
    • 直到调用onServiceConnected()mServicenull。因此,在您非常确定 onServiceConnected() 将被调用之前,您不想调用 mService 上的方法。因此,例如,当用户可以点击某个东西时,mService 可能已经准备好了。但是,onResume() 为时过早——您的bindService() 请求可能尚未处理。
    • 我已经尝试过了,它抑制了崩溃,但现在onServiceConnected() 没有被击中......
    猜你喜欢
    • 2020-08-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多