Timed and cell-phone notifications

3

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

The home screen is where the service starts, 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 be started when the phone is switched on (like Whatsapp shows message notifications when we turn on the phone).

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?

    
asked by anonymous 12.04.2015 / 08:49

1 answer

5

To run a service when the phone is switched on you have to register a BroadcastReceiver that responds to action android.intent.action.BOOT_COMPLETED .

In 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" />

Set BroadcastReceiver to 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 define a method to record the notifications. This method uses AlarmManager to launch a BroadcastReceiver that will create notifications on the date / time specified in the date parameter. Call this method for every 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();

Set the BroadcastReceiver that will be released 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 in AndroidManifest.xml .

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

Notes:

  • You must run 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 phone memory.
12.04.2015 / 13:45