How to run a task in the background

0

I'm new to android programming and I've been doing an application for myself so far. In this app I want when it goes into the background, that is, when I exit the application without calling the onDestroy () method, a task will start to run.

When I exit the application it starts a timer 15 minutes, when the time runs out it will be called a webservice to check if I have any new alerts.

I would like to know if I can indicate some library or tutorial that I can use

    
asked by anonymous 17.05.2017 / 16:22

1 answer

0

Hello,

You can create a service:

  

A Service is an application component that can perform long operations and does not provide a user interface. Another component of the application can start a service and it will continue to run in the background even if the user switches to another application. In addition, a component can bind to a service to interact with it and even establish interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I / O, or interact with a content provider, all from the background ....    link

A simple example of what you need:

Create the service class

public class TarefaBackground extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    long seconds;
    public Sleeper(String name) {
        super(name);
    }

    public Sleeper() {
        super("");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        long millis = 900000;
        Toast.makeText(this, "OnHandle", Toast.LENGTH_LONG).show();
        while(true) {
            try {
                Thread.sleep(millis);
                System.out.println("executou ação");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Add within the Application tag in manifests

<service
    android:name=".TarefaBackground">
</service>

Finally in mainActivity

@Override
    protected void onPause() {
        super.onPause();
        Intent intent= new Intent(MainActivity.this,TarefaBackground.class);
        startService(intent);

    }
    
17.05.2017 / 16:58