简体   繁体   English

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

[英]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. 我有一个BroadcastReceiver,可以启动我的服务,该服务使用异步方式发出HTTP请求,然后显示通知,但我没有让系统每次自动启动,然后每1分钟启动一次。

Here is my AndroidManifest: 这是我的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: 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);
    }
}

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 我现在做了一些更改,我迷路了,甚至看不到创建服务的日志,只有日志BroadcastReceiver

You will have to use AlarmManager to start your service. 您将必须使用AlarmManager来启动服务。 To use AlarmManager, you need a pending Intent which you want the alarm to fire. 要使用AlarmManager,您需要一个挂起的Intent,您希望它触发警报。 like so: 像这样:

  1. First, create a Receiver that will will be fired by an Intent, 首先,创建一个将由Intent触发的Receiver,

  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.使用警报管理器来激发待定意图。
  4. Remember, your Receiver will fire your service via Intent when it receives content from your alarm manager. 请记住,当接收器从警报管理器接收内容时,接收器将通过Intent触发服务。 You can use the setRepeating method of alarmManager to set the repeat time. 您可以使用alarmManager的setRepeating方法来设置重复时间。

Look at this stack overflow post for example How to start Service using Alarm Manager in Android? 看看这个堆栈溢出的帖子,例如如何在Android中使用Alarm Manager启动服务? .

For details, checkout this link(Using with AlarmManager for Periodic Tasks) https://guides.codepath.com/android/Starting-Background-Services 有关详细信息,请检查此链接(与AlarmManager一起使用以执行定期任务) https://guides.codepath.com/android/Starting-Background-Services

Hope this help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM