我有一个 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 的日志
我是一名优秀的程序员,十分优秀!