Helio Soares Junior
Helio Soares Junior

Reputation: 447

How to start a service when system boot and repet every 1 minute

I have a BroadcastReceiver that starts my service, this service it uses async to make an HTTP request and then display a notification, but I'm not getting the service to be run every time the system starts automatically, and then every 1 minute.

Here is my AndroidManifest:

<receiver android:name=".notificar.InicializarServico" android:exported="false">
    <intent-filter>
        <action android:name="INICIALIZAR_SERVICO"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</receiver>
<service android:enabled="true" android:name=".notificar.ServicoNotificar">
    <intent-filter>
        <action android:name="SERVICO_ATUALIZAR"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</service>

The code of BroadcastReceiver is here:

public class InicializarServico extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("NAMURA LANCHES", "O SISTEMA FOI INICIADO");
        Log.v("NAMURA LANCHES", "Iniciando o serviço de atualização");
        // Preparar Intent para inicializar o serviço
        agendar(context, 5);
        Log.v("NAMURA LANCHES", "O Serviço sera iniciado em 15 segundos");

    }

    private void agendar(Context context, int i) {
        Intent myIntent = new Intent(context, ServicoNotificar.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,  0, myIntent, 0);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, i); // first time
        long frequency= i * 1000; // in ms
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
    }
}

And here is my service class:

public class ServicoNotificar extends Service{

private String RequestURL = "http://sandbox.omeuprofissional.com/requests/meus_pedidos.php";
private final int duration = 3000;
private static final String ACTION_RESCHEDULE =
        "br.com.namuralanches.android.intent.action.SERVICE_RESCHEDULE";
Handler myHandler;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    Thread testThread;
    boolean threadRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        myHandler = new Handler();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("NAMURA LANCHES", "Service started");
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                SharedPreferences preferencias = getSharedPreferences("mesa", MODE_PRIVATE);
                String registro = preferencias.getString("REGISTRO_MESA", null);
                String hashMesa = preferencias.getString("HASH_MESA", null);

                if ((registro != null) || (hashMesa != null)) {
                    new ListarCompras().execute(RequestURL, hashMesa, registro);
                }
            }
        }, 10000);

        stopSelf(startId);
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.v("NAMURA LANCHES", "SERVICO DESTRUIDO");
        super.onDestroy();
        threadRunning = false;
    }
}

I made some changes now I'm lost, I'm not even see the log that the service was created, only the log BroadcastReceiver

Upvotes: 1

Views: 83

Answers (1)

Aliyu Abdullahi
Aliyu Abdullahi

Reputation: 129

You will have to use AlarmManager to start your service. To use AlarmManager, you need a pending Intent which you want the alarm to fire. like so:

  1. First, create a Receiver that will will be fired by an Intent,

  2. in your activity, create the intent that fires the Receiver,

  3. create a pending intent for the intent that fires the receiver, finally 4. use alarm manager to fire the pending intent.
  4. Remember, your Receiver will fire your service via Intent when it receives content from your alarm manager. You can use the setRepeating method of alarmManager to set the repeat time.

Look at this stack overflow post for example How to start Service using Alarm Manager in Android?.

For details, checkout this link(Using with AlarmManager for Periodic Tasks) https://guides.codepath.com/android/Starting-Background-Services

Hope this help.

Upvotes: 0

Related Questions