I am developing an App which is based on certain notification by which user performs an action I want to show notification and after notification I want to add add Time + 5 minutes to show next notification. and also run Timer process in background when app is closed.
public long Time = 3600;
private NotificationManagerCompat notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
Timer();
}
public void Timer() {
for (long i = Time; i < 86400000; i = i += 60000) {
new CountDownTimer(1000, i) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
ShowNotification();
}
}.start();
}
}
public void ShowNotification() {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setContentTitle("Example")
.setContentText("Example Action")
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.build();
notificationManager.notify(1, notification);
}
Try AlarmReceiver in that case.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, 2);
Intent intent = new Intent("android.action.DISPLAY_NOTIFICATION");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
Related
I have an arrayList in the MainActivity, and I'm using alarmManager to show notifications when the app is closed. I don't know how I can use that arraylist in the BroadcastReceiver "inside onReceive() method" and get data from that arraylist to show it in the Notifications. I also want to be able to remove the element from the arraylist that has already been shown in the notification.
anyway this my code, I hope you can help me !
-MainActivity :
NotificationManager mNotificationManager;
int NOTIFICATION_ID = 0;
private static final String ACTION_NOTIFY = "com.example.android.standup.ACTION_NOTIFY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent notifyIntent = new Intent(ACTION_NOTIFY);
final PendingIntent notifyPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
ToggleButton toggleButton = findViewById(R.id.alarmToggle);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
long triggerTime = SystemClock.elapsedRealtime()+10000;
long repeatInterval = 180000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, repeatInterval, notifyPendingIntent);
}else {
mNotificationManager.cancelAll();
alarmManager.cancel(notifyPendingIntent);
}
}
});
}
AlarmReceiver Class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent contentIntent = new Intent(context, MainActivity.class);
PendingIntent contentPendingIntent = PendingIntent.getActivity
(context, createID(), contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hello")
.setContentText("Notification Text")
.setContentIntent(contentPendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
notificationManager.notify(createID(), builder.build());
}
public int createID(){
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
return id;
}
}
Thank you !
I am new on android. I want to show notification on a particular date and time(For e.g on date 9 September 2017 on time 10:00 AM) in my app. I am using alarm manager but it does not work properly.
Please tell me the proper way.
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2017);
calendar.set(Calendar.MONTH, 9);
calendar.set(Calendar.DAY_OF_MONTH, 9);
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent inn = new Intent(MainActivity.this,AlarmActivity.class);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0,inn, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
}
AlarmActivity
public class AlarmActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content_alarm);
final Intent notificationIntent = new Intent(this, AlarmActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(AlarmActivity.this, 0, notificationIntent, 0);
Notification notification1 = new Notification.Builder(AlarmActivity.this)
.setContentTitle("Notification")
.setContentText("Get Notigication")
.setContentIntent(contentIntent).setWhen(System.currentTimeMillis())
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification1);
}
Manifest
Permission
In order to trigger alarm you have to use WakefulBroadcastReceiver from where you will trigger a service that will generate notification in you activity.
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Then you will create a service like this.
public class AlarmService extends IntentService {
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
contentId = intent.getStringExtra("id");
String title = intent.getStringExtra("title");
String subtitle = intent.getStringExtra("subtitle");
sendNotification(title, subtitle);
}
public void sendNotification(String title, String subtitle) {
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.reminder_notification_view);
contentView.setInt(R.id.layout, "setBackgroundColor",
Color.WHITE);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, subtitle);
notification.contentView = contentView;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notification.contentIntent = PendingIntent.getActivity(this, someRandomId,
intent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
mNotificationManager.notify(someRandomId, notification);
}
}
I have tried alarmanager in order to get daily notification in android.... The alarm do start at specified time but gets repeated every minute after that...I have specified INTERVAL_DAY in setrepeating() function of Mainactivity but it does not seems to work. It contains three parts Mainactivity, MyReceiver & AlarmService. Can anyone seems to fix this ??
Mainactivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
// we can set time by open date and time picker dialo
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(MainActivity.this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(this.ALARM_SERVICE);
Log.e("Tag","calling here");
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),864000, pendingIntent);
}
}
MyReceiver
public class MyReceiver extends BroadcastReceiver{
int MID=0;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.icon)
.setContentTitle("Alaram Fired")
.setContentText("Events To be PErformed").setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(MID, mNotifyBuilder.build());
MID++;
}
}
MyAlarmService
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
Log.e("Tag1","alarmservice here");
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.icon,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notification.setLatestEventInfo(this.getApplicationContext(), "Daily Notification Demo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
AlarmManager.setRepeating doesn't work properly on different android versions.
Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:
Update MyReceiver
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, (864000 + System.currentTimeMillis()),pendingIntent);
Here we schedule alarm again by calculating nextAlarmTime using 864000 + System.currentTimeMillis();
I created a method to send a notification to the user named sendNotification () using NotificationCompat.Builder and NotificationManager.
I need this notification to be posted at a fixed interval of 24 hours or even at a specific time, for example every day at 07:00 AM, which in this case would result in the same 24 hours, which may be adjusted by the user in the future.
It seems to me that with the public class AlarmManager it is possible to perform this procedure, but I am not sure if I have to create a service or if it would be the service itself.
How could this notification be done within this 24-hour ?
public void setLocalNotification(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(this, LocalNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 99, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Log.d("TAG ","LocalNotification Start");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pendingIntent);
}
public class LocalNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TUS-NOTAS ", "LocalNotification Receiver");
Intent service1 = new Intent(context, ShowNotificationService.class);
context.startService(service1);
}
}
public class ShowNotificationService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private final static String TAG = "ShowNotification";
public ShowNotificationService()
{
super("ServiceNotification");
}
public ShowNotificationService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
Context context = this.getApplicationContext();
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, SplashActivity.class);
pendingIntent = PendingIntent.getActivity(context,99, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getResources().getString(R.string.app_name));
builder.setVibrate(new long[] { 200, 200});
builder.setSound(uri);
if (Global.getStringKey(getApplicationContext(), Definitions.LANGUAGE_VALUE).equals("en"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("We miss you!"));
builder.setContentText("You have not added any notes recently.");
}else if (Global.getStringKey(getApplicationContext(),Definitions.LANGUAGE_VALUE).equals("es"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Te extrañamos!"));
builder.setContentText("No has agregado notas recientemente.");
}
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo_app);
builder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Log.d("TUS-NOTAS"," LocalNotification Service");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
}
}
0 0 7 1/1 * ? *
This is a cron statement made from http://www.cronmaker.com/. You can use this in a cron job that executes everyday at 7 am.
I want to generate notification everyday at 8:00 AM. I have created the code for simple notification but I am not getting the notification following is the code for NotifyService Class
public class NotifyService extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*Notification Related*/
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Thought")
.setContentText("Get Today's Thought");
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
//mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
And this is the code written in the MainActivity class onCreate method
PendingIntent pendingIntent;
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY,8);
calendar1.set(Calendar.MINUTE,00);
calendar1.set(Calendar.SECOND,00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);
Don't know where I am getting wrong
I don't think you have created a service here. Notifyservice class extends AppCompatActivity. You should extend Service class to make it a service.
Best solution for your problem can be found with the following steps
Create a service for alarmnotification
Create a receiver to start the service of alarmnotification
add the receiver and service into manifest.xml too
Follow the steps of given url.
http://karanbalkar.com/2013/07/tutorial-41-using-alarmmanager-and-broadcastreceiver-in-android/
MainActivity
public class MainActivity extends AppCompatActivity {
AlarmManager alarmManager;
PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Button setAlarm= (Button)findViewById(R.id.button);
setAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 00);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 10, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
});
}
}
AlarmReceiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Intent startIntent = new Intent(context, NotificationService.class);
context.startService(startIntent);
Log.e("TRIGGER", "ALARM TRIGGERED");
}
}
NotificationService
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Intent inn=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
inn, 0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test Message")
.setContentText("Hi, you have one notification");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Add this in your AndroidManifest file
<receiver android:name=".AlarmReceiver"></receiver>
<service android:name=".NotificationService"/>