Search code examples
androidwebsocketandroid-activity

Start activity from a background-thread


I have an andoid-app that connects to a WebSocket-server when the user logs in. If the user is idle for some time or for whatever reason his session expires/terminates, the application gets notified through the WebSocket-connection and I want to take him back to the login-activity (there is no functionality in the application if he is not logged in).

I have looked into broad-casting Intents and the runOnUIThread() but can't seem to get it to work. An idea I have is to simply register the running activity (have all of them implement an interface for example) and make a call but that would mean all Activities would have to implement the interface. Most of them already inherits from a BaseActivity-class but not all of them.

I realize its bad practice to disrupt the user-flow abruptly, but none of the functionality will work unless the user have a valid session.

Im using the android-websocket (https://github.com/koush/android-websockets) library as a client if that makes any difference.

Thanks in advance Tomas

EDIT: Sometimes I would also like to inform the user in the form of a Toast or Dialog that a certain event happened on the server.


Solution

  • I think any of these two approaches should work:

    • Use a Handler: Set a Handler in your Activity, override its handleMessage so when you send a message to it, you simply bring your Activity to the front (or start it). To bring it to front:

      Intent i = new Intent(this, MyMainActivity.class);
      i.setAction(Intent.ACTION_MAIN);
      i.addCategory(Intent.CATEGORY_LAUNCHER);
      startActivity(i);
      
    • Use a BroadcastReceiver: There's no reason why this shouldn't work, simply declare your receiver, register it for some action (might be customized) and start the activity the same way than above. Don't forget to unregister it once you're done or you close your app.

    If you need an example on any, just ask for it.