Running Android Services

Asked 2 years ago, Updated 2 years ago, 26 views

Hello. I made a CCTV app that can be used remotely by mobile phone <-> using webRTC.

I always want to run this CCTV app in the background.

First of all, the main activity is...

In the service class, you tried to run activity on the background stage in this way, but it failed.

Is there any way to always run activity?

It's an app that connects CCTV with cell phone ID B from cell phone A I wanted to make sure that A can always connect even if the app is not turned on on on cell phone B, so I thought of service, but it's blocked. I'd appreciate your help.

 Context context =getApplicationContext();
 Intent intent = new Intent(context, MainActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 context.startActivity(intent);

android

2022-09-22 21:26

1 Answers

You said you tried to run an activity on the service, but it didn't. First of all, it is necessary to check if the service is alive at this point, but the activity is not running, or if it is caused by the service being interrupted. From personal experience, it seems likely that it will be the latter.

The service may be interrupted by the system. (Quote Google Docs)

Android systems are forced to stop services only when there is insufficient memory and the user must recover system resources for focused activity. If the service is bound to an activity that is attracting your attention, it is unlikely to be interrupted, and if the service is declared to be running in the foreground (discussed in detail later), it is rarely interrupted. Otherwise, if the service is started and running for a long time, over time, the system will gradually lower the position of this service in the background task list and the service will become very easy to stop.

When the system stops the service, the onStartCommand() function returns determine whether the service should be restarted. Make sure you return START_STICKY as shown in the code below.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    ...

    // // If we get killed, after returning from here, restart
    return START_STICKY;
}

Finally, please read Run the service in the foreground of the link below before applying it.

In the event of low memory, activity in the background state (down to the background) is more likely to be terminated by the system than activity in the foreground state. The same rules apply to services, so if you run them in the foreground, you can prevent disruptions in advance.


2022-09-22 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.