Sometimes context.startActivity(intent) not working in a class that extends WebSocketServer in Android

32 Views Asked by At

I have a class that extends WebSocketServer and waits for a request from the client application and if a message arrives, it should run an activity. The code below shows how this works. Note that the application that runs the code below runs in the background and currently the client application has the screen. If the first request from the client application arrives, the desired activity runs correctly and appears on the screen, but later with the arrival of requests, this does not happen. The context used in this code has no problem because it runs correctly the first time. I also have no problem receiving messages because the messages are received properly from the client. Can you help me understand where the problem comes from?

Note: Android 11

public class WBServer extends WebSocketServer {

@Override
public void onMessage(WebSocket conn, String message) {

        Intent intent = new Intent(MyApplication.getInstance().context, ThirdPartyActivity.class);
        intent.putExtra("TransType", 1);
        intent.putExtra("Amount", String.valueOf(12000));
        intent.putExtra("ResNum", "1111111111111111111111111");
        intent.putExtra("AppId", "1");
        intent.putExtra("Timer",60_000);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        MyApplication.getInstance().context.startActivity(intent);

        conn.send("Text to client");
}
}

How can we make sure that the desired activity always runs?

1

There are 1 best solutions below

3
logancodemaker On

If your WBServer is running in background then you cannot start an activity from a backgroud service in android 11 refer to the documentation https://developer.android.com/guide/components/activities/background-starts