如何保持应用程序服务在前台和后台处于活动状态

时间:2019-04-12 13:10:34

标签: java android sockets client-server background-service

如何使我的应用保持在Socket服务器上的连接并在前台和后台运行。我需要从服务器接收一些通知和数据。 到目前为止,我的应用程序仅在打开,关闭或仅返回连接时才起作用。

并且当应用程序关闭并且用户再次运行应用程序并尝试再次连接到服务器时,连接没有发生,那么我需要重新启动服务器并再次连接。

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            iSocketInterface = ISocketInterface.Stub.asInterface(iBinder);
            socketServiceBound = true;

        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {

            iSocketInterface = null;
            socketServiceBound = false;

        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, SocketService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    protected void onRestart(){
        super.onRestart();

    }

    protected void onResume(){
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onStop() {
                super.onStop();
}

0 个答案:

没有答案
相关问题