How to repeat a minute-by-minute notification

2

I'm creating a app Simple receiving a notification every time I click a button of my layout , everything works perfectly. Now I want this notification be repeated for example every minute until I disable it. Can anyone give me a hint how can i do this ?? :).

Here is my code.

public class MainActivity extends Activity {
    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.main);
        Button createNotification = (Button) findViewById
                (R.id.create_notification_button);
        createNotification.setOnClickListener (new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                Intent intent = new Intent (MainActivity.this ,
                        notificationActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity
                        (MainActivity.this, 0, intent, 0);
                Notification notification = new Notification.Builder (MainActivity.this)
                        .setContentTitle(getString(R.string.new_notification))
                        .setContentText(getString (R.string.notification_content))
                        .setSmallIcon (R.drawable.ic_launcher)
                        .setContentIntent(pendingIntent)
                        .getNotification();
                notification.flags = Notification.FLAG_AUTO_CANCEL;
                NotificationManager notificationManager =
                        (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
                notificationManager.notify (0, notification);
            }
        });
    }
}
    
asked by anonymous 02.02.2017 / 19:35

3 answers

5

Create a service that by using a HandlerThread uses the Handler to launch notifications periodically.

public class NotifyService extends Service {

    private HandlerThread handlerThread;
    private Handler handler;

    //Define o tempo entre notificações, altere como quiser
    private final int TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS = 10;

    @Override
    public void onCreate() {
        Log.d("NotifyService","onCreate");

        handlerThread = new HandlerThread("HandlerThread");
    }

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

        Log.d("NotifyService","onStart");

        //Previne que seja executado em subsequentes chamadas a onStartCommand
        if(!handlerThread.isAlive()) {
            Log.d("NotifyService","Notificações iniciadas");
            handlerThread.start();
            handler = new Handler(handlerThread.getLooper());

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    sendNotification();
                    handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
                }
            };
            handler.post(runnable);
        }
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("NotifyService","Notificações terminadas");
        handlerThread.quit();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void sendNotification(){
        Intent intent = new Intent (this ,
                notificationActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity
                (this, 0, intent, 0);
        Notification notification = new Notification.Builder (this)
                .setContentTitle(getString(R.string.new_notification))
                .setContentText(getString (R.string.notification_content))

                .setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pendingIntent)
                .getNotification();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager =
                (NotificationManager) getSystemService (NOTIFICATION_SERVICE);
        notificationManager.notify (0, notification);
        Log.d("NotifyService", "notificação enviada");
    }
}

Declare the service in AndroidManifest.xml

<application>
    ...
    ...
    <service
        android:name=".NotifyService"
        android:exported="false" />
</application>

To start creating notifications use:

startService(new Intent(this, NotifyService.class));

Notifications will be released with the time interval indicated in TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS , even if it exits the application.

To stop notifications use:

stopService(new Intent(this, NotifyService.class))

Example with two buttons, one to start and one to stop:

public class MainActivity extends Activity {

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView (R.layout.activity_main);

        Button startNotification = (Button)findViewById(R.id.start_notification_button);
        Button stopNotification = (Button)findViewById(R.id.stop_notification_button);

        startNotification.setOnClickListener (new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                startService(new Intent(MainActivity.this, NotifyService.class));
            }
        });

        stopNotification.setOnClickListener (new View.OnClickListener() {
            @Override
            public void onClick (View v) {
                stopService(new Intent(MainActivity.this, NotifyService.class));
            }
        });
    }
}
    
03.02.2017 / 23:06
3

There are several ways to do this, but you can use ScheduledExecutorService in a Service . Here's how it would look:

public class MyService extends Service {

    // definição do loop de 60 em 60 segundos, equivalente a 1 min
    private static final int SECONDS = 60 ;

    // indica inicilização
    int mStartMode;

    //interface para clientes
     IBinder mBinder;

    //indica se o onRebind está sendo usado
    boolean mAllowRebind;

    private ScheduledExecutorService sTaskExecutor;

    @Override
    public void onCreate() {
        Toast.makeText(this, "Serviço iniciado!!", Toast.LENGTH_SHORT).show();
        sTaskExecutor = Executors.newScheduledThreadPool(1);
    }

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

        if (!sTaskExecutor.isShutdown()) {
            sTaskExecutor.scheduleAtFixedRate(new Runnable() {
                public void run() {

                    /* aqui você insere a notificação  */
                    android.util.Log.wtf(MyService.class.getSimpleName(), " Em loop!!!");
                }
            }, 0, SECONDS, TimeUnit.SECONDS);
        }

        return mStartMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return mAllowRebind;
    }

    @Override
    public void onDestroy() {
        sTaskExecutor.shutdown();
        Toast.makeText(this, "Serviço finalizado!!", Toast.LENGTH_SHORT).show();
    }
}

In Manifest :

<application>
    ...
     <service android:name=".MyService" android:exported="false"/>
</application>

To START the Service user method startService in your class MainActivity . See:

startService(new Intent(getBaseContext(), MyService.class));

For STOP the% co_of% user the Service method. See:

stopService(new Intent(getBaseContext(), MyService.class));

For more details, you can see the documentation .

    
02.02.2017 / 19:42
0

You can also use AlarmManager to manage notifications.

First create a class that extends BroadcastReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class DispararNotificacao extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // faz o que vc precisa aqui para disparar sua notificação
    }
} 

Then just add the request to AlarmManager within your onClick

Calendar calendar = Calendar.getInstance();

Intent tarefaIntent = new Intent(getApplicationContext(), DispararNotificacao.class);

PendingIntent tarefaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 
    requestCode, tarefaIntent, PendingIntent.FLAG_CANCEL_CURRENT);

final long inteval = minuto * 60 * 1000;

AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
    inteval, tarefaPendingIntent);

To disable notifications, just cancel at AlamrManager

Intent tarefaIntent = new Intent(getApplicationContext(), DispararNotificacao.class);
PendingIntent tarefaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 
    requestCode, tarefaIntent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(tarefaPendingIntent);
    
03.02.2017 / 22:04