为什么startService()和bindService()仅在活动中使用时才起作用? onStart()方法?

时间:2015-07-24 04:09:52

标签: java android android-service android-service-binding

最初,我尝试使用MainActivity中的函数启动和绑定我的服务,如下所示:

public void startTimerService(){
    Intent intent = new Intent(this, TimerService.class);
    startService(intent);

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("MainActivity", "onServiceConnected");
            TimerService.LocalBinder binder = (TimerService.LocalBinder) iBinder;
            timerService = binder.getService();
            boundToTimer = true;

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            boundToTimer = false;
            Log.d("MainActivity", "onServiceDisconnected");
        }
    };
    Intent intent2 = new Intent(this, TimerService.class);

    bindService(intent2, mConnection, Context.BIND_AUTO_CREATE);
    timerService.startTimer();
}

当我尝试访问timerService.startTimer();时,这给了我一个nullPointerException但是,当我将代码移动到onStart()方法时:

@Override
public void onStart(){
    super.onStart();
    Intent intent = new Intent(this, TimerService.class);
    startService(intent);

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("MainActivity", "onServiceConnected");
            TimerService.LocalBinder binder = (TimerService.LocalBinder) iBinder;
            timerService = binder.getService();
            boundToTimer = true;

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            boundToTimer = false;
            Log.d("MainActivity", "onServiceDisconnected");
        }
    };
    Intent intent2 = new Intent(this, TimerService.class);

    bindService(intent2, mConnection, Context.BIND_AUTO_CREATE);
}

并且只在timerService.startTimer();方法中调用startTimerService()方法调用,一切正常。唯一的问题是我不知道为什么会这样,也许有人可以启发我。

0 个答案:

没有答案
相关问题