Notifications in a given time and on mobile phone

Asked

Viewed 2,751 times

3

Hello. I’m making an android app that notifies me when I have to deliver a school assignment and, if it’s the day of the task or the day before, I want to be notified at certain times.

The home screen is where the service is started, where I click on "Tasks" to go to Task Activity.

public class DashboardActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard_activity);

    startService(new Intent(this, ShowNotificationService.class));
}
}

But I would like the service to start when the phone was turned on (as Whatsapp shows messages notifications when we turn on the mobile).

Code of showNotificationService.class

public class ShowNotificationService extends Service {

private EducInDAO dao;
private DatabaseHelper helper;
private Context context;

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

@Override
public void onCreate() {
    super.onCreate();
    helper = new DatabaseHelper(this);
    try {
        tarefas();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

public void tarefas() throws ParseException {
    SQLiteDatabase db = helper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM tarefas", null);

    if (cursor == null) {

    } else {
        while(cursor.moveToNext()) {

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dataEntrega = new Date(cursor.getLong(2));
            Date dateNow = new Date();

            String dataEntregaFormatada = sdf.format(dataEntrega);
            String dateNowFormatada = sdf.format(dataEntrega);

            GregorianCalendar calendar = new GregorianCalendar();
            int hora = calendar.get(Calendar.HOUR_OF_DAY);


            if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 0) || (dateNowFormatada.compareTo(dataEntregaFormatada) == 1)) {
                int id = cursor.getInt(0);
                String nomeMateria = cursor.getString(1);

                String title = "Eae, já fez?";

                if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 0)) {
                    if ((hora == 0 || hora == 7 || hora == 12 || hora == 23)) {
                        if ((hora == 0 || hora == 7 || hora == 12)) {
                            String contentText = "Você tem tarefa de " + nomeMateria + " para hoje!";
                            Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
                            v.vibrate(1000);
                            showNotification(title, contentText, id, 1);
                        }
                    }
                } else if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 1)) {
                    if ((hora == 15 || hora == 18 || hora == 22)) {
                        String contentText = "Você tem tarefa de " + nomeMateria + " para amanhã!";
                        Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
                        v.vibrate(1000);
                        showNotification(title, contentText, id, 1);
                    }
                }
            }
        }
    }

    cursor.close();
}


public void showNotification(String title, String content, int id, int tipoNotificacao) {

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(title)
            .setContentText(content)
            .setAutoCancel(true);;

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    if (tipoNotificacao == 1) {
        mBuilder.setSmallIcon(R.drawable.homework);

        Intent resultIntent = new Intent(this, TarefasActivity.class);
        resultIntent.putExtra(Constantes.TAREFA_ID, String.valueOf(id));

        stackBuilder.addParentStack(TarefasActivity.class);
        stackBuilder.addNextIntent(resultIntent);
    }

    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(id, mBuilder.build());
}

}

But what happens is that it shows the notifications, for example, at 10 pm but if I take the notification, it appears again! So it’s take that shows again :/

How to solve?

1 answer

5


To run a service when the mobile phone is turned on you have to register a Broadcastreceiver to respond to action android.intent.action.BOOT_COMPLETED.

In the Androidmanifest.xml register your Broadcastreceiver:

<receiver android:name="aSuaPackage.StartUpBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>  

Add this permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Define the Broadcastreceiver that will launch your service:

public class StartUpBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            // Chame aqui o seu serviço
        }
    }
}  

In the service set a method to record notifications.
This method uses the Alarmmanager to launch a Broadcastreceiver which will create the notifications at the date/time specified in the parameter date.
Call this method for each notification you want to create.

private void AgendarNotificacao(Date data) {

 // Obtém um novo calendário e define a data para a data da notificação
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(data);

 // Obtém um alarm manager
    AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);

 // O id a ser usado no pending intent
    int id = (int) System.currentTimeMillis();

 // Prepara o intent que deverá ser lançado na data definida
    Intent intent = new Intent(this, CriarNotificacao.class);

 // Obtém o pending intent
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 // Regista o alerta no sistema.
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}  

As you have more than one type of notification enter the parameters you need to build the notification. Pass this information to Intent through Intent.putExtra();

Define the Broadcastreceiver which will be launched by the Alarmmanager registered by the previous method. This Broadcastreceiver is responsible for creating the notification.

public class CriarNotificacao extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent paramIntent) {

    // Obtenha os 'Extra' que passou e crie aqui a notificação

}

Register it on Androidmanifest.xml.

<receiver android:name="aSuaPackage.CriarNotificação"/>  

Notes:

  • It is necessary to execute the application once before it can respond to android.intent.action.BOOT_COMPLETED action. The same applies if your execution has been stopped using Force Close.
  • The application needs to be installed in the cellular memory.
  • Hello, thank you for the reply. I did what you asked, but it didn’t work. Follow the modified code: http://pastebin.com/fgYui4W8

  • Did you register Create Notification on Androidmanifest.xml.? I forgot to put that detail in the answer.

  • I’ve been going through your code, and I don’t think you understand how to use the Scheduling method. You must pass to the method the date and time you want to be notified. Suppose you have a task for the date 16/04/2015 at 18h and want to be notified 3 hours before, you must subtract from the date of the task 3 hours and call the method with the result. Use the class Calendar to build the date to pass the method. Do not forget that when saying date I am not just referring to the day, month and year, but also to the time, minute and second at which the notification is to be launched.

  • Thank you very much! As soon as possible I will try to implement the xD solution

  • It worked! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.