How to run a task in the background

Asked

Viewed 588 times

1

I am new to android programming and have been making an application for myself so far. In this app I want that when it goes into the background, that is, when you leave the application without calling onDestroy() method, start running a task.

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

I wonder if you can give me some library or tutorial I can use

1 answer

1

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 application component can launch a service and it will continue running in the background even if the user switches to another application. In addition, a component may link to a service to interact with it and even establish inter-process communication (IPC). For example, a service can handle network transactions, play music, run I/O files, or interact with a content provider, all from the background.... https://developer.android.com/guide/components/services.html

A simple example for 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 inside the Application tag in the manifests

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

Finally on the mainActivity

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

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.