有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

最初,我尝试使用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);
}

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


共 (0) 个答案