从未在onBind()被调用时调用Android Studio Services onServiceConnected()

时间:2018-12-01 22:26:42

标签: android android-studio service

在我的应用中,我正在使用绑定服务。但是,在运行代码时,我启动了服务并绑定到该服务(OnBind()方法起作用),但是此后从不调用OnStartService(),并且我的服务等于null。

这是我的服务代码:

public class MyService extends Service{

boolean toExit = false;
boolean isThreatDetectionOn;

boolean isDanger = false;
int counter;

class MyServiceBinder extends Binder {
    public MyService getService()
    {
        return MyService.this;
    }
}



@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.i("Bind", "thats good");
    return null;
}

@Override
public void onDestroy() {
    stop();

    super.onDestroy();

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    isThreatDetectionOn = true;




    new Thread(new Runnable() {
        @Override
        public void run() {
            start();
        }
    }).start();
    return START_STICKY;
}
}

start()和stop()是在服务中运行的方法,分别开始生成随机数和停止生成随机数。

以下是该服务的绑定/取消绑定代码:

private MyService ListeningService;
private boolean isServiceBound = false;
private ServiceConnection serviceConnection;


bindService = (Button) findViewById(R.id.button7);
    bindService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {
            Log.i("Great","Button Bind Clicked");
            if(serviceConnection == null)
            {
                Log.i("Great","Service Connection is Null");
                serviceConnection = new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                        MyService.MyServiceBinder myBinder = (MyService.MyServiceBinder)iBinder;
                        listeningService = myBinder.getService();
                        isServiceBound = true;
                        Log.i("Yes", "Service Connected");
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName componentName) {
                        isServiceBound = false;
                        Log.i("No", "Service DisConnected");
                    }
                };
            }

            bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        }
        });

    unbindService = (Button) findViewById(R.id.button8);
    unbindService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isServiceBound)
            {
                unbindService(serviceConnection);
                isServiceBound = false;
                Log.i("No", "Service DisConnected");
            }
        }
    });

即使在调用onBind()之后(在日志中显示“ Bind:thats good”),isServiceBound仍保持为false,因为它现在已连接服务,因此现在应该变为true。

0 个答案:

没有答案