@Override protected void onHandleIntent(Intent intent) { running = true; // Este método executa em uma thread // Quando ele terminar, o método stopSelf() será chamado automaticamente int count = 0; while (running && count < MAX) { fazAlgumaCoisa(); Log.d(TAG, "ExemploServico executando... " + count); count++; } NotificationUtil.create(this,1,new Intent(this,MainActivity.class),R.mipmap.ic_launcher,"Fim","Olá"); Log.d(TAG, "ExemploServico fim."); } private void fazAlgumaCoisa() {
public void run() { try { while (running && count < MAX) { // Simula algum processamento Thread.sleep(1000); Log.d(TAG, "HelloService executando... " + count); count++; } Log.d(TAG, "HelloService fim."); } catch (InterruptedException e) { Log.e(TAG,e.getMessage(),e); } finally { // Auto-Encerra o serviço se o contador chegou a 10 stopSelf(); // Cria uma notificação para avisar o usuário que terminou. Context context = HelloService.this; Intent intent = new Intent(context,MainActivity.class); NotificationUtil.create(context, 1, intent, R.mipmap.ic_launcher, "HelloService", "Fim do serviço."); } } }
@Override public void onReceive(Context context, Intent intent) { Log.d(TAG, ">" + intent.getAction()); Sms sms = new Sms(); // Lê a mensagem SmsMessage msg = sms.read(intent); String celular = msg.getDisplayOriginatingAddress(); String mensagem = msg.getDisplayMessageBody(); Log.d(TAG, "SMSReceiver: sms[" + celular + "] -> " + mensagem); NotificationUtil.create(context, 1, new Intent(context, MainActivity.class), R.mipmap.ic_launcher, "Novo SMS de: " + celular, mensagem); } }