如何在系统启动时启动服务并每1分钟重复一次

时间:2016-01-31 22:40:33

标签: java android service broadcastreceiver

我有一个启动我的服务的BroadcastReceiver,这个服务使用异步来发出HTTP请求,然后显示一个通知,但我没有让每次系统自动启动时运行服务,然后每1个分钟。

这是我的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>

BroadcastReceiver的代码在这里:

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);
    }
}

这是我的服务类:

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;
    }
}

我做了一些更改,现在我迷路了,我甚至没有看到服务创建的日志,只有日志BroadcastReceiver

1 个答案:

答案 0 :(得分:0)

您必须使用AlarmManager启动服务。要使用AlarmManager,您需要一个希望触发警报的待处理Intent。 像这样:

  1. 首先,创建一个将由Intent触发的Receiver,

  2. 在您的活动中
  3. ,创建触发Receiver的意图

  4. 为触发接收器的意图创建待定意图,最后4.使用警报管理器触发待处理的意图。
  5. 请记住,当接收到来自警报管理器的内容时​​,您的Receiver将通过Intent触发您的服务。您可以使用alarmManager的setRepeating方法设置重复时间。
  6. 请查看此堆栈溢出帖子,例如How to start Service using Alarm Manager in Android?

    有关详细信息,请查看此链接(使用AlarmManager进行定期任务) https://guides.codepath.com/android/Starting-Background-Services

    希望得到这个帮助。