How to make application running in the background all the time

Asked

Viewed 9,780 times

5

I tried to use the Service as they said but it’s not working yet. I don’t know if I got it right, the method onStartCommand() will run all the time? Because I debug and the application only enters this method once, when the onCreate() is called and I need what’s there run all the time. Follow the code:

Java service.

public class Servico extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("oi", "onStartCommand");
        boolean ok = true;
        while(ok == true){
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            gerarNotificacao();
       }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Executaservico.java

public class ExecutaServico extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent pushIntent = new Intent(context, Servico.class);
            context.startService(pushIntent);
        }
    }
}

Androidmanifest.xml

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".ExecutaServico">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name=".Servico"/>

        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Mainactivity.java

 public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(HomeActivity.this,Servico.class));
        final Button continuar = (Button) findViewById(R.id.btn_continuar);
        continuar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        //varias coisas
            }
       });
   }
}

I have no idea what I did wrong... Every 30 seconds the notification should appear

1 answer

8


What you need is a Service, it runs even when your application is closed, and you can make it run even if the user restarts the device.

First of all, let’s create your service class

Testservice.java

public class TestService extends Service
{
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        // START_STICKY serve para executar seu serviço até que você pare ele, é reiniciado automaticamente sempre que termina
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

In the second step, let’s create a BroadcastReceiver to notify the service to be started as soon as the device starts.

Bootcompletedintentreceiver.java

public class BootCompletedIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent pushIntent = new Intent(context, TestService.class);
            context.startService(pushIntent);
        }
     }
}

Now we will also state in your MainActivity for her to start the service.

Mainactivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(getBaseContext(), TestService.class));
}

Finally, we must declare in Manifest the Service, the BroadcastReceiver and permission to start the service as soon as the device finishes booting.

Manifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <application>
  <receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <service android:name=".TestService"/>
 </application>

Doing so you will get a service that runs all the time, even if the device is restarted.


Some links that can help you too:

Autostart Service on Device Boot

How to Automatically Restart a service Even if user force close it?

Android Services - Tutorial

Services | Android Developers

  • I did what you said, but it’s not working. It’s giving this error: "Activitythread: Performing stop of Activity that is not resumed"

  • 1

    It worked, I just changed the call from Service to onPause(), because otherwise the application would not open... Thank you! I’m sorry I asked you another question, I needed this, and I didn’t know if you’d be back in time

  • Ok, I’m glad it worked out, there is also the possibility to restart the service if the user forces the shutdown

  • how do I restart the service in the case of a force Closer? @Vitorhenrique

Browser other questions tagged

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