0

I want to create a notification that works every 5 minute,for example. For this, I use BroadCastReceiver. Here is my code:

   public void notifyMe()
   Calendar calendar = Calendar.getInstance() ;

    calendar.set(Calendar.HOUR,0);

    calendar.set(Calendar.MINUTE,5);

    calendar.set(Calendar.SECOND,0);


    Log.d("tagger",calendar.getTime().toString());



    Intent intent = new Intent(this,MyBroadcastReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5*60*1000,sender);
   }

Also for Receiver:

public class MyBroadcastReceiver extends BroadcastReceiver {

private static final int NOTIFY_ID = 101;



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

    Log.d("BroadcastReceiver", "debut receive");


    Intent resultIntent  =  new Intent(context,DetailActivity.class) ;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(context)
            .setContentTitle("title")
            .setContentText("some text");

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(resultPendingIntent);

    int id = 001 ;

    NotificationManager mNotifyManager = (NotificationManager)context.getSystemService(Application.NOTIFICATION_SERVICE);

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

Manifest:

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".PrefsApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" />
    <activity android:name=".ActionsActivity"

        ></activity>

    <receiver android:name=".MyBroadcastReceiver">



    </receiver>
</application>

What it doesn't work? I didn't forget to add receiver to the manifest. I need to use Service instead of Receiver?

neo
  • 1,314
  • 2
  • 14
  • 34

2 Answers2

1

Try this:

 private void notificationManager(Context context, String message) {

    try {
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Log.v("message", "," + message);

        Intent notificationIntent = new Intent(context, SplashActivity.class);


        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setContentTitle(context.getString(R.string.app_name));
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        builder.setContentText(message);
        builder.setTicker(message);
        builder.setLights(Color.GREEN, 500, 500);
        builder.setWhen(when);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(intent);


        Notification notification = builder.build();
        notification.ledARGB = 0xFFff0000;
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        notification.ledOnMS = 100;
        notification.ledOffMS = 100;
        notificationManager.notify(1, notification);

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Hope this helps.

Sarthak Gandhi
  • 2,130
  • 1
  • 16
  • 23
  • This works. Is it repeating notification,that works even after closing app?And also where did you set a time for notification? On acquire(15000) or it is set when declaring receiver? Also as I've read , this method affects to the battery negativily. – neo Jul 09 '17 at 07:59
  • int the setWhen method. you can run a service that notifies after every 5 mins. Use the countdowntimer class for that. – Sarthak Gandhi Jul 09 '17 at 08:02
  • That method is waking up the screen. – Sarthak Gandhi Jul 09 '17 at 08:09
  • You can use TimerTask class and its method scheduleAtFixedRate(). – Sarthak Gandhi Jul 09 '17 at 08:10
1

Update notifyMe() method as below to set repeating alarm:

public void notifyMe()

    // Current time
    Calendar calendar = Calendar.getInstance() ;
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.SECOND, 0);

    Log.d("tagger", calendar.getTime().toString());

    Intent intent = new Intent(this, MyBroadcastReceiver.class);    
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Set alarm
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);

    // Or you can also use
    //am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);
}    

Update MyBroadcastReceiver as below:

public class MyBroadcastReceiver extends BroadcastReceiver {

    private static final int NOTIFY_ID = 101;

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

        Log.d("BroadcastReceiver", "debut receive");

        // Intent to start activity 
        Intent resultIntent  =  new Intent(context, DetailActivity.class) ;
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification mNotification = new Notification.Builder(context)
            .setContentTitle("Title")
            .setContentText("Some text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent).build();


        NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyManager.notify(NOTIFY_ID, mNotification);
    }
}
Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • That didn't work for me. Why we need `calendar.getTimeInMillis()` ? I know that it returns current time in millis. – neo Jul 09 '17 at 10:18
  • `calendar.getTimeInMillis()` returns this calendar's time value in milliseconds. For your case, as we are setting `System.currentTimeMillis()` and not setting specific year, month, day, hour, min that's why it will return current time. We are using this current time to set first alarm. – Ferdous Ahamed Jul 09 '17 at 10:24
  • If not triggered, then check logcat to konw `Log.d("BroadcastReceiver", "debut receive");` is printed or not. – Ferdous Ahamed Jul 09 '17 at 10:27
  • It is printed. I also created button that shows that notification. It worked. Maybe I have to use Service? – neo Jul 09 '17 at 10:43
  • You don't need service for this purpose. Your notification did not created properly. Check my updated answer and try again. – Ferdous Ahamed Jul 09 '17 at 11:13
  • Because you are setting current time for first alarm. – Ferdous Ahamed Jul 09 '17 at 11:39
  • If you want to set alarm to specific time and repeat then set your desired day, month, year, hour and minute. Check this: https://stackoverflow.com/questions/12649288/how-to-set-java-util-calendar-to-a-specific-time-period-in-the-future – Ferdous Ahamed Jul 09 '17 at 11:45
  • Thanks fro accepting my answer. If it seems useful, hope you will give an up-vote too. Thank you~ – Ferdous Ahamed Jul 09 '17 at 11:58
  • Thanks dear. Happy coding :) – Ferdous Ahamed Jul 09 '17 at 12:12