【问题标题】:service got stopped when the app goes background当应用程序进入后台时服务停止
【发布时间】:2016-08-10 13:33:33
【问题描述】:

您好,在项目中,我正在使用 SignalR 进行聊天通信服务。聊天通信工作正常,但是当应用程序进入后台时,服务停止了,我需要完全运行服务,直到我的应用程序被删除

这是我的服务代码

public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients

public SignalRService() {
}

@Override
public void onCreate() {
    super.onCreate();
    mHandler = new Handler(Looper.getMainLooper());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int result = super.onStartCommand(intent, flags, startId);
    startSignalR();
    return result;
}

@Override
public void onDestroy() {
    Log.i("onDestroy","onDestroy");
    mHubConnection.stop();
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Return the communication channel to the service.
    startSignalR();
    return mBinder;
}

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    public SignalRService getService() {
        // Return this instance of SignalRService so clients can call public methods
        return SignalRService.this;
    }
}

/**
 * method for clients (activities)
 */
public void sendMessage(String message) {
    String SERVER_METHOD_SEND = "Send";
    mHubProxy.invoke(SERVER_METHOD_SEND, message);
}

/**
 * method for clients (activities)
 */
public void sendMessage_To(String receiverName, String message) {
    String SERVER_METHOD_SEND_TO = "SendChatMessage";
    mHubProxy.invoke(SERVER_METHOD_SEND_TO, receiverName, message);
}

private void startSignalR() {
    Platform.loadPlatformComponent(new AndroidPlatformComponent());
    Credentials credentials = new Credentials() {
        @Override
        public void prepareRequest(Request request) {
            request.addHeader("User-Name", "BNK");
        }
    };

    String serverUrl = "http://10.10.10.180/signalr/hubs";
    mHubConnection = new HubConnection(serverUrl);
    mHubConnection.setCredentials(credentials);
    String SERVER_HUB_CHAT = "ChatHub";
    mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
    ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
    SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);

    try {
        signalRFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e("SimpleSignalR", e.toString());
        return;
    }

    sendMessage("Hello from BNK!");

    String CLIENT_METHOD_BROADAST_MESSAGE = "broadcastMessage";
    mHubProxy.on(CLIENT_METHOD_BROADAST_MESSAGE,
            new SubscriptionHandler1<CustomMessage>() {
                @Override
                public void run(final CustomMessage msg) {
                    final String finalMsg = msg.UserName + " says " + msg.Message;
                    // display Toast message
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("message","message: "+finalMsg);
                            Toast.makeText(getApplicationContext(), finalMsg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
            , CustomMessage.class);
}}

这是活动代码

public class MainActivity extends AppCompatActivity {

private final Context mContext = this;
private SignalRService mService;
private boolean mBound = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent();
    intent.setClass(mContext, SignalRService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    // Unbind from the service
    Log.i("onStop","onStop");
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
    super.onStop();
}

public void sendMessage(View view) {
    if (mBound) {
        // Call a method from the SignalRService.
        // However, if this call were something that might hang, then this request should
        // occur in a separate thread to avoid slowing down the activity performance.
        EditText editText = (EditText) findViewById(R.id.edit_message);
        EditText editText_Receiver = (EditText) findViewById(R.id.edit_receiver);
        if (editText != null && editText.getText().length() > 0) {
            String receiver = editText_Receiver.getText().toString();
            String message = editText.getText().toString();
            mService.sendMessage_To(receiver, message);
            mService.sendMessage(message);
        }
    }
}

/**
 * Defines callbacks for service binding, passed to bindService()
 */
private final ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {
        // We've bound to SignalRService, cast the IBinder and get SignalRService instance
        SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {

        Log.i("onServiceDisconnected","onServiceDisconnected");

        mBound = false;
    }
};}

我的服务清单代码

<service
        android:name=".SignalRService"
        android:enabled="true"
        android:exported="true" >
    </service>

请帮我解决这个问题

【问题讨论】:

    标签: android service signalr android-service


    【解决方案1】:

    如果您将服务与任何组件绑定,如果没有其他客户端绑定,系统将自动销毁该服务。

    如果你想独立运行一个服务,那么你必须启动一个服务而不是绑定。但是如果你用startService()启动一个服务,你就不能和它通信

    更多详情可以查看文档here

    【讨论】:

    • 如果我删除 unbindService(mConnection);从 onStop 应用程序崩溃
    • 您能否提供此类服务的任何样本,因为我是服务新手
    • 我需要做客户端-服务器接口,我可以在 startService() 方法上做吗
    • 我使用 BroadcastReceiver 实现了相同的功能,但我知道这不是最好的解决方案。但是有些我如何设法为我工作。你可以试试这个。 :)
    • 你有那种类型的示例代码,我也可以试试吗?我想不通
    【解决方案2】:

    您可以启动和绑定服务。

    这样,即使多个组件同时绑定到服务,然后全部解除绑定,服务也不会不会被销毁。参考A service can essentially take two forms: Bound

    您的服务可以以两种方式工作:它可以启动(无限期运行)并且还允许绑定。这只是你是否实现几个回调方法的问题:onStartCommand() 允许组件启动它,onBind() 允许绑定。

    // onBind method just return the IBinder, to allow clients to get service.
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
    // onStartCommand just return START_STICKY to let system to
    // try to re-create the service if the servcie's process is killed.
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
    // and make startSignalR public to allow client to call this method.
    public void startSignalR() {
    }
    

    在您的客户端中,无需保留布尔值 mBound

    onCreate 时绑定服务,onDestroy 时取消绑定服务。当onStop 时不要解绑。由于onStop 可能会调用多次,例如弹出对话框会调用onStop,但您的活动仍在前台,这将导致您的服务被破坏。

    示例代码参考my answer for question: Pass Service From one Activity to Another

    【讨论】:

      猜你喜欢
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多