Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in 'Editor & General Support' started by danielesuppo, Nov 29, 2016.

  1. danielesuppo

    danielesuppo

    Joined:
    Oct 20, 2015
    Posts:
    331
    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
    https://forum.unity3d.com/threads/a...s-not-working-on-android.117723/#post-2838437
    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/
     
    games504, ZiadJ, mgear and 1 other person like this.
  2. chamberlainpi

    chamberlainpi

    Joined:
    Feb 8, 2009
    Posts:
    1
    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.
     
    ZiadJ likes this.
  3. Yury-Habets

    Yury-Habets

    Unity Technologies

    Joined:
    Nov 18, 2013
    Posts:
    1,167
    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)
     
  4. tomerpeledNG

    tomerpeledNG

    Joined:
    Jul 14, 2017
    Posts:
    81
    How will the service helps us? Will our FixedUpdates functions will be called?
    Can you please provide some information about it?

    Thanks
     
  5. Yury-Habets

    Yury-Habets

    Unity Technologies

    Joined:
    Nov 18, 2013
    Posts:
    1,167
    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).
     
  6. Krunal_vasundhara

    Krunal_vasundhara

    Joined:
    Apr 27, 2017
    Posts:
    35
    can i call update method of unity continuously in background using this?
    bacause it wont work? have you solution for that?
     
  7. danielesuppo

    danielesuppo

    Joined:
    Oct 20, 2015
    Posts:
    331
    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...
     
  8. Krunal_vasundhara

    Krunal_vasundhara

    Joined:
    Apr 27, 2017
    Posts:
    35
    Can you show me demo
     
  9. danielesuppo

    danielesuppo

    Joined:
    Oct 20, 2015
    Posts:
    331
    I'll look for this old project and I'll send you
     
  10. Krunal_vasundhara

    Krunal_vasundhara

    Joined:
    Apr 27, 2017
    Posts:
    35
    okay no problem i will wait.
     
  11. danielesuppo

    danielesuppo

    Joined:
    Oct 20, 2015
    Posts:
    331
  12. heemun

    heemun

    Joined:
    Apr 15, 2014
    Posts:
    18
    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.
     
  13. jordano00

    jordano00

    Joined:
    Jul 3, 2016
    Posts:
    10
    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
    Code (CSharp):
    1. public class UnityPlayerActivity extends Activity
    2. {
    3.     protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code
    4.  
    5.     // Setup activity layout
    6.     @Override protected void onCreate(Bundle savedInstanceState)
    7.     {
    8.         requestWindowFeature(Window.FEATURE_NO_TITLE);
    9.         super.onCreate(savedInstanceState);
    10.  
    11.         mUnityPlayer = new UnityPlayer(this);
    12.         setContentView(mUnityPlayer);
    13.         mUnityPlayer.requestFocus();
    14.     }
    15.  
    16.     @Override protected void onNewIntent(Intent intent)
    17.     {
    18.         // To support deep linking, we need to make sure that the client can get access to
    19.         // the last sent intent. The clients access this through a JNI api that allows them
    20.         // to get the intent set on launch. To update that after launch we have to manually
    21.         // replace the intent with the one caught here.
    22.         setIntent(intent);
    23.     }
    24.  
    25.     // Quit Unity
    26.     @Override protected void onDestroy ()
    27.     {
    28.         mUnityPlayer.quit();
    29.         super.onDestroy();
    30.     }
    31.  
    32.    /* // Pause Unity
    33.     @Override protected void onPause()
    34.     {
    35.         super.onPause();
    36.         mUnityPlayer.pause();
    37.     }*/
    38.  
    39.     // Resume Unity
    40.     @Override protected void onResume()
    41.     {
    42.         super.onResume();
    43.         mUnityPlayer.resume();
    44.     }
    45.  
    46.     @Override protected void onStart()
    47.     {
    48.         super.onStart();
    49.         mUnityPlayer.start();
    50.     }
    51.  
    52.     @Override protected void onStop()
    53.     {
    54.         super.onStop();
    55.         mUnityPlayer.stop();
    56.     }
    57.  
    58.     // Low Memory Unity
    59.     @Override public void onLowMemory()
    60.     {
    61.         super.onLowMemory();
    62.         mUnityPlayer.lowMemory();
    63.     }
    64.  
    65.     // Trim Memory Unity
    66.     @Override public void onTrimMemory(int level)
    67.     {
    68.         super.onTrimMemory(level);
    69.         if (level == TRIM_MEMORY_RUNNING_CRITICAL)
    70.         {
    71.             mUnityPlayer.lowMemory();
    72.         }
    73.     }
    74.  
    75.     // This ensures the layout will be correct.
    76.     @Override public void onConfigurationChanged(Configuration newConfig)
    77.     {
    78.         super.onConfigurationChanged(newConfig);
    79.         mUnityPlayer.configurationChanged(newConfig);
    80.     }
    81.  
    82.     // Notify Unity of the focus change.
    83.     @Override public void onWindowFocusChanged(boolean hasFocus)
    84.     {
    85.         super.onWindowFocusChanged(hasFocus);
    86.         mUnityPlayer.windowFocusChanged(hasFocus);
    87.     }
    88.  
    89.     // For some reason the multiple keyevent type is not supported by the ndk.
    90.     // Force event injection by overriding dispatchKeyEvent().
    91.     @Override public boolean dispatchKeyEvent(KeyEvent event)
    92.     {
    93.         if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
    94.             return mUnityPlayer.injectEvent(event);
    95.         return super.dispatchKeyEvent(event);
    96.     }
    97.  
    98.     // Pass any events not handled by (unfocused) views straight to UnityPlayer
    99.     @Override public boolean onKeyUp(int keyCode, KeyEvent event)     { return mUnityPlayer.injectEvent(event); }
    100.     @Override public boolean onKeyDown(int keyCode, KeyEvent event)   { return mUnityPlayer.injectEvent(event); }
    101.     @Override public boolean onTouchEvent(MotionEvent event)          { return mUnityPlayer.injectEvent(event); }
    102.     /*API12*/ public boolean onGenericMotionEvent(MotionEvent event)  { return mUnityPlayer.injectEvent(event); }
    103. }
    104.  
     
  14. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    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.
     
    Last edited: Nov 26, 2018
  15. jordano00

    jordano00

    Joined:
    Jul 3, 2016
    Posts:
    10
    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.
     
  16. jordano00

    jordano00

    Joined:
    Jul 3, 2016
    Posts:
    10
    I might have to scrap the app idea for now until unity has new features appropriate for the app.

    There goes my 15$ :'(
     
  17. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    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?
     
  18. 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
     
  19. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    424
    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)?
     
  20. theriyazsaifi_unity

    theriyazsaifi_unity

    Joined:
    Apr 1, 2019
    Posts:
    5
    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.
     
  21. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    Does this still work in new Unity versions 2018/19?
     
  22. MD_Reptile

    MD_Reptile

    Joined:
    Jan 19, 2012
    Posts:
    2,664
    Unity and running in the background is not the easiest thing to do. If you absolutely require unity applications on mobile to continue running in the background - you don't want the unity activity going because it burns through battery life but rather a background service with native code, doing the bare minimum to make your app not set phones on fire.

    Read more here, and then Google it:
    https://stackoverflow.com/questions/50967370/run-code-in-background-unity
     
  23. fcevallos

    fcevallos

    Joined:
    Apr 5, 2019
    Posts:
    4
    Yo pude correr una aplicacion mobil hecha en Unity en Background, utilizando servicios nativos de android.
     
  24. mikeswar

    mikeswar

    Joined:
    Mar 4, 2019
    Posts:
    1
    Me podrías decir como lo lograste? Como funciona eso de servicios nativos de android? :confused:o_O
     
  25. fcevallos

    fcevallos

    Joined:
    Apr 5, 2019
    Posts:
    4
    Hola, si claro, solo que es algo complicado de explicar:
    1. Abres android Studio, y le das en New -> Jar Library, luego ahi codificas tu servicio nativo en android.. una vez que funciona, le das en BUILD, y exportas el JAR, ese jar, lo pones en Asstes/plugins/android/
    junto con tu manifest, donde declaraste tu servicio.
    2. en tu script, tienes que llamar al metodo que declaraste en Android Studio, como, packagename.NOMBREMETODO.

    es un poco complejo de realizar la verdad, yo me tarde muchisimo tiempo, pero si deseas que te explique de forma mas directa, escribeme a mi correo, Frank7cevallos@gmail.com
     
  26. nintendaii

    nintendaii

    Joined:
    Dec 16, 2019
    Posts:
    14
    GuenterWolf, abj2023 and CrandellWS like this.
  27. CrandellWS

    CrandellWS

    Joined:
    Oct 31, 2015
    Posts:
    178
  28. ThisIsDangerous

    ThisIsDangerous

    Joined:
    Dec 3, 2018
    Posts:
    39
    I haven't tried the hacky workaround mentioned earlier nor did I try to make a service. But since there is a lot of talk about running a foreground activity and battery burning and coffee making, I have to ask...
    Why should it burn?
    Suppose you can run your application in the background. The application you make will do just what you code it to do. Make it 1 frame per second and don't do heavy calculations and stop rendering while it's out of focus. This way the application should behave CPU- and battery-wise the same or closely the same as a service then? No? Why?
     
  29. nintendaii

    nintendaii

    Joined:
    Dec 16, 2019
    Posts:
    14
    The thing is that you CAN NOT run your app in the background. You can only run it in foreground as a notification channel and then you are able to hide it in settings. This foreground service will behave as a normal service (you can check that it in Developer setting / Running services. You should definitely check my plugin I mentioned in previous post.
     
  30. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    758
    And there have anyway to do in iOS?