简体   繁体   中英

How can I keep my app running in the background on iOS/Android with libGDX

I'm using libGDX and I want to keep my application running even when it's closed to send push notifications/alerts to the user. I need to do this for both iOS and Android.

You will need to Implement a Service on android and create an interface for it. Basically this is going to be platform dependent code for your game .

  1. Create an Interface AndroidPushNotificationServiceCallback;

     public interface AndroidPushNotificationServiceCallback { public void startService(); public void sendPushNotification(); public void stopService(); } 
  2. Then make your main GameListener constructor have this listener as a parameter

      public class MainGameListener extends ApplicationListener{ public MainGameListener(AndroidPushNotificationServiceCallback callback) this.callback = callback; } 
  3. Then make your android mainactivity implement this interface

     public class MainActivity extends AndroidApplication implements AndroidPushNotificationServiceCallback{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); cfg.useGL20 = true; cfg.useAccelerometer=false; cfg.useCompass=false; initialize(new MainGameListener(), cfg); } public void startService(){ // start a service here } public void sendPushNotification(){ // send push notifcations here } public void stopService(){ // stop the service here } } 

Now in your gamelistener you need to call the method to start the service on the callback. the callback implementation will then start the service.

This is just a dummy example . Plus this approach is generic , use it in any situation you want to call platform specific methods.

Once the service is started, it can set alarms and other stuff to periodically invoke code (like sending push notification in your case)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM