Android app is actually running in background! - It work!

Hello all,
sometimes you need your Android app running in background, for some reason (GPS location, time events, etc), and as you know Unity pause when it’s out of focus. So most of threads say that it’s impossible to do, if not with a dedicated native Android service running… to hard to do, at least for me, expecially if your stuffs are running on Unity (and not on the service).

BUT… I’ve found another thread from glassfin that gave to me a solution to this “issue”, without no coding at all and very easy to implement, and I’m glad to share it with you (and maybe someone much more skilled than me can give his opinion on it).
Here is the thread

I’ve tried it with a very small project (no dependecies or external .dll for now).
This can be thought as a forcing to the system, but it work!

1 - Build settings / Android - Check “Google Android Project”
2 - Export in some folder
3 - Go to your folder, search and open the file “UnityPlayerActivity.java” (it should be under /src/com/yourcompany/scenefile/)
4 - Edit this file commenting out the calling on the Pause
5 - Import it in Android Studio
6 - Build you .apk (from Android Studio)

That’s all!
Yor app will be running in background!!!

Let me know about it
And many thanks to glassfin!!!
https://forum.unity3d.com/members/glassfin.1157706/

4 Likes

Hey congratz on getting that to work! I’m after a very similar functionality, but I’m not 100% certain that the steps you provided are ideal in terms of conserving battery life. Then again I’m still relatively new to Unity and completely rookie with Android.

You or someone else can correct me if I’m wrong, but wouldn’t your method run your entire Unity app in the background (not just the GPS location aspect)? which is a bit overkill - well I guess unless you’re doing some other runtime calculations in Unity that are important to your game / app in the background.

But if all you need is GPS locations, sounds to me like it would be better to let the Unity app idle/sleep/hide when the Android device is locked or whatever, and isolate the dedicated Android Background Service to run the GPS location independently in the background (maybe you want to fill up an array of longitude/latitude to pass back to your Unity game once you reopen it).

Easier said than done though! I know I’ve googled and browsed through a few examples to grasp how to build an Android Background Service for Unity and the project setup alone is a PITA, and I can only imagine what sort of hoops one has to jump through to debug and ensure the service runs optimally (especially if your users are going to run this often in the background).

Did you experience your app to drain the battery any faster than usual with your method? Or is it running reasonably on devices?

In the short term, I think I may try out your way (just to get our prototype out the door), but I do believe a background service would be recommended at some point in development.

1 Like

This is wrong, it’s breaking the activity lifecycle.
(also the battery, as mentioned by @chamberlainpi )
To have your app running in the background, implement a service. (requires some effort)

How will the service helps us? Will our FixedUpdates functions will be called?
Can you please provide some information about it?

Thanks

Yes, you just need to have a Service instead of an Activity. Sorry I have no samples - try searching or reading up on the docs (even better).

can i call update method of unity continuously in background using this?
bacause it wont work? have you solution for that?

Helllo Krunal_vasundhara, it’s been a long time from my post, but as far as I can remember I was using a counter in Update, so it should work…

Can you show me demo

I’ll look for this old project and I’ll send you

okay no problem i will wait.

Here’s the link to the test project
https://www.dropbox.com/s/3gi4n1dau2qca5z/UnityTest_runInBackground.rar?dl=0
I had no time to test it again, and I can’t guarantte that’s working with last Unity version, hopefully it will help you.

Hi guys.
I’ve tried to access Unity via Android service and SendUnityMessage. Still i cannot call any Unity methods if the application is turned off or is running in background.

Hi Daniel,

I tried the following steps that you did but it doesn’t seem to be working. im using 2017.4.1.
What I’m trying to do with my app is the app listens to the phrase that the user is saying outside the app (when app is on background) and play music if a certain phrase is said.

The voice recognition works outside the app and so does the music part but the problem is that i need to open the app again in order for the music to play instead of playing immediately after the app heard the phrase while the app is on background.

this is my java code by gradle

public class UnityPlayerActivity extends Activity
{
    protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code

    // Setup activity layout
    @Override protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        mUnityPlayer = new UnityPlayer(this);
        setContentView(mUnityPlayer);
        mUnityPlayer.requestFocus();
    }

    @Override protected void onNewIntent(Intent intent)
    {
        // To support deep linking, we need to make sure that the client can get access to
        // the last sent intent. The clients access this through a JNI api that allows them
        // to get the intent set on launch. To update that after launch we have to manually
        // replace the intent with the one caught here.
        setIntent(intent);
    }

    // Quit Unity
    @Override protected void onDestroy ()
    {
        mUnityPlayer.quit();
        super.onDestroy();
    }

   /* // Pause Unity
    @Override protected void onPause()
    {
        super.onPause();
        mUnityPlayer.pause();
    }*/

    // Resume Unity
    @Override protected void onResume()
    {
        super.onResume();
        mUnityPlayer.resume();
    }

    @Override protected void onStart()
    {
        super.onStart();
        mUnityPlayer.start();
    }

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

    // Low Memory Unity
    @Override public void onLowMemory()
    {
        super.onLowMemory();
        mUnityPlayer.lowMemory();
    }

    // Trim Memory Unity
    @Override public void onTrimMemory(int level)
    {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_RUNNING_CRITICAL)
        {
            mUnityPlayer.lowMemory();
        }
    }

    // This ensures the layout will be correct.
    @Override public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        mUnityPlayer.configurationChanged(newConfig);
    }

    // Notify Unity of the focus change.
    @Override public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);
        mUnityPlayer.windowFocusChanged(hasFocus);
    }

    // For some reason the multiple keyevent type is not supported by the ndk.
    // Force event injection by overriding dispatchKeyEvent().
    @Override public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
            return mUnityPlayer.injectEvent(event);
        return super.dispatchKeyEvent(event);
    }

    // Pass any events not handled by (unfocused) views straight to UnityPlayer
    @Override public boolean onKeyUp(int keyCode, KeyEvent event)     { return mUnityPlayer.injectEvent(event); }
    @Override public boolean onKeyDown(int keyCode, KeyEvent event)   { return mUnityPlayer.injectEvent(event); }
    @Override public boolean onTouchEvent(MotionEvent event)          { return mUnityPlayer.injectEvent(event); }
    /*API12*/ public boolean onGenericMotionEvent(MotionEvent event)  { return mUnityPlayer.injectEvent(event); }
}

I think it should be stressed that having a unity activity running constantly in the background is a terrible idea. This will drastically reduce battery life, if it even works at all anymore. You users will not be happy with this, and it will make the OS probably not very happy. You need to setup either a native activity or service of some kind, that does “light” background work, and only read back in whats happened when the user opens the app again - because that way won’t eat through the devices battery (and actually works). Sorry to say, I have tried, and it is difficult, but with time and research this can be done.

EDIT: Even if it did work - in addition to wasting tons of battery, it would likely be force closed all the time on systems without much memory to spare. There are all sorts of problems with trying this hack-y workaround. The only situation something like this might make sense, is if your building some app that turns androids into coffee warmers.

That would probably be the case. But I can’t think of any workaround for my app to work as I want it to work.
I was thinking of doing like a widget on the notification bar (similar to the widget for a music app on the notification bar) but I dont know how to do that and I don’t know the keywords to use to search for it.

I might have to scrap the app idea for now until unity has new features appropriate for the app.

There goes my 15$ :cry:

Well, I wouldn’t be so quick to give up (though, that is challenging), until you have exhausted every option. Look into the possibility of writing a native service… the info is out there, you just gotta do some more work than a magic “leave unity running all the time” solution. Perhaps - dare I say - don’t use unity at all?

This is something you should develop in Android Studio instead.

And if you want notification you should start somewhere around here: https://developer.android.com/training/notify-user/build-notification

Hi there! I need to run unity code when app is in background (android). I wrote Service, but it’s working only if app not paused. Should i use another service-like solution? Is it possible at all (call unity methods from service when app in background)?

This method is no more working,
I was trying to keep update my count down timer but every time i go background its stop updating.