I'm struggling with sending multiple notifications at separate times. For example, I want to be able to send a push notification at 8:30, 9:00, 9:30 (for argument's sake) but it keeps sending a notification at the end. I really need saving. I thought sending push notifications would be much easier with Android.
This is my MainActivity.java code
package com.nerdoidis.localpushnotificationdemo;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
ArrayList<String> times;
public void getTimes() {
times = new ArrayList<>();
times.add("5:25");
times.add("5:26");
times.add("5:27");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTimes();
for (int x = 0; x < times.size(); x++) {
String time = times.get(x).toString();
String[] timeSplit = time.split(":");
int hour = Integer.parseInt(timeSplit[0]);
int minute = Integer.parseInt(timeSplit[1]);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
String formattedTime = df.format(c.getTime());
String[] formattedTimeSplit = formattedTime.split(":");
int hourNow = Integer.parseInt(formattedTimeSplit[0]);
int minuteNow = Integer.parseInt(formattedTimeSplit[1]);
if (hour > hourNow && minute > minuteNow) {
//Do nothing for now
} else {
Notification notification = getNotification("Your Next Shuttle is at " +
times.get(x).toString());
scheduleNotification(notification, 1, hour, minute);
}
}
}
private void scheduleNotification(Notification notification, int id, int hour, int minute) {
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(this, id, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
}
private Notification getNotification(String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Shuttle Time");
builder.setContentText(content);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(false);
return builder.build();
}
}
My "Broadcast Receiver" type class
package com.nerdoidis.localpushnotificationdemo;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by MarumoJohannesTsesan on 10/17/2017.
*/
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Added it to the manifest as well with the following line
<receiver android:name=".NotificationPublisher" />
I'm still struggling though big time!
Related
I am registering the alarm when system reboot since alarm will be killed after the system rebooted, but I get the error of 'Cannot resolve method getSystemService()', is it syntax error...
can Context be used in this case since this function should be called when the phone has been rebooted...
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class RebootBroadcast extends BroadcastReceiver {
private static final String LOG_TAG = "MyBroadcast ";
public RebootBroadcast () {
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context,1,intent,0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService();
AlarmManager alarmManager2 = (AlarmManager) context.getSystemService();
long timeAtButtonClick = System.currentTimeMillis();
long tenSecondsInMillis = 1000 * 10;
long nextInMillis = 1000 * 20;
String myDate = "2020/05/09 18:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
long millis = date.getTime();
//long diff = millis - timeAtButtonClick;
alarmManager.set(AlarmManager.RTC_WAKEUP, millis, pendingIntent);
break;
default:
break;
}
}
}
}
You should change to
(AlarmManager) context.getSystemService()
(AlarmManager) context.getSystemService(Context.ALARM_SERVICE)
You need to call getSystemService on a Context, hence, why it doesn't work in your ALARM_SERVICE. You can store the context you already pass in as a field and call getSystemService on that.
I faced error
developer warning for package "package name" fail to post
notification on channel "null" more see in Logcat
can anyone help me with a normal app that uses TimePicker to set the time ..and also uses intents,etc instead of normal comparisons.This is the code that i've done till now.But this is not working. The 'TimePicker' sets the time and on pressing the 'ToggleButton' a 'TextVew' shows that alarm is on .But when the alarmtime is reached,Alarm Ringing message is not shown.Please someone help me out. this is the code of main activity
AlarmNotificationReceiver
package com.example.kishorsinh.yogaapp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent in = new Intent(context, ListExercises.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, in, 0);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.yoga)
.setContentTitle("It's About Time")
.setContentText("text.... ")
.setContentInfo("text....")
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
Setting Page
package com.example.kishorsinh.yogaapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.example.kishorsinh.yogaapp.Database.YogaDB;
import java.util.Calendar;
import java.util.Date;
public class SettingPage extends AppCompatActivity {
Button btnSave;
RadioButton rdiEasy,rdiMedium,rdiHard;
RadioGroup rdiGroup;
YogaDB yogaDB;
ToggleButton switchAlarm;
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_page);
//init view
btnSave = (Button) findViewById(R.id.btnSave);
rdiGroup = (RadioGroup) findViewById(R.id.rdiogroup);
rdiEasy = (RadioButton) findViewById(R.id.rdioEasy);
rdiMedium = (RadioButton) findViewById(R.id.rdioMedium);
rdiHard = (RadioButton) findViewById(R.id.rdioHard);
switchAlarm = (ToggleButton) findViewById(R.id.switchAlarm);
timePicker = (TimePicker) findViewById(R.id.timePicker);
yogaDB = new YogaDB(this);
int mode = yogaDB.getSettingMode();
setRadioButton(mode);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveWorkoutMode();
saveAlarm(switchAlarm.isChecked());
Toast.makeText(SettingPage.this, "Saved!!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void saveAlarm(boolean checked) {
if(checked)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
//Set time for alarm
Calendar calendar = Calendar.getInstance();
Date toDay = Calendar.getInstance().getTime();
if (Build.VERSION.SDK_INT >= 23 ) {
//new version mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getHour(), timePicker.getMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getHour() + ":" + timePicker.getMinute());
}
else
{
//olderversion mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute());
}
}
else
{
//Cancel Alarm
Intent intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
private void saveWorkoutMode() {
int selectedID = rdiGroup.getCheckedRadioButtonId();
if(selectedID == rdiEasy.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 30sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(0);
}
else if(selectedID == rdiMedium.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 20sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(1);
}
if(selectedID == rdiHard.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 10sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(2);
}
}
private void setRadioButton(int mode) {
if(mode == 0)
rdiGroup.check(R.id.rdioEasy);
else if(mode == 1)
rdiGroup.check(R.id.rdioMedium);
else if(mode == 2)
rdiGroup.check(R.id.rdioHard);
}
}
.
.
..
.
.
.
.
...........................................................................................................
package com.example.agniva.demoapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
public class Alarm extends BroadcastReceiver implements PaymentServiceListener {
Database database;
ArrayList<String> log_arrlist;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Log.e("I am in", "Alarm onReceive");
database = new Database(context);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
database.add_log("Alarm !!!!!!!!!!" + "\n");
wl.release();
Cursor cursor = database.getAllLog();
log_arrlist = new ArrayList<>();
if (cursor.moveToFirst()) {
Log.e("Cursor Object>>>>>>>", DatabaseUtils.dumpCursorToString(cursor));
do {
String allLog = cursor.getString(cursor.getColumnIndex("fld_log_name"));
Log.e("allLog", ">>>" + allLog);
log_arrlist.add(allLog);
for (int z = 0; z < log_arrlist.size(); z++) {
Log.e("LOG", "ARRAY>>" + log_arrlist.get(z));
}
// do what ever you want here
} while (cursor.moveToNext());
}
cursor.close();
Intent background = new Intent(context, EmergencyService.class);
context.startService(background);
/** Service Call is not working here */
PaymentService paymentService = new PaymentService(context, log_arrlist);
paymentService.execute();
}
public void setAlarm(Context context) {
Log.e("I am in", "Alarm setAlarm");
/*AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("com.example.agniva.demoapp.START_ALARM");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);*/
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("com.example.agniva.demoapp.START_ALARM");
alarmIntent = PendingIntent.getBroadcast(context, 0, i, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
5 * 1000, alarmIntent);
}
#Override
public void onGettingPaymentResponse(String result) {
Log.e("Result", ">>" + result);
}
}
It shows Unable to start receiver com.example.agniva.demoapp.Alarm: java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to com.example.agniva.demoapp.PaymentServiceListener
Payment Service don't found the context here. Is it possible to call a web service here? Please give me any suggestion or link if you have. Or is there any other way to call a web service in AlarmManager.
The Context that the Receiver expones is not a common Context as you expect. A Receiver could live even without an Activity or a Service so the Context is NOT yours and neither one of your Classes. I think you cast the Context to PaymentServiceListener but it's illegal. You can use that Context to extract Strings or start/launch Services/Activities/Threads but cannot be casted to one of your Classes.
I am new to android development and have very little knowledge in java and I have seen this Alarm Clock app tutorial in the internet. The application has problems. It can't set time before the current time of phone and it doesn't start at the exact time. How to make this application so it can set alarm within 24 hours and at the exact time?
AlarmActivity.java
package com.javapapers.androidalarmclock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
AlarmReceiver.java
package com.javapapers.androidalarmclock;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmService.java
package com.javapapers.androidalarmclock;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Please Help! I am desperate.
If you want to have a 24hour span, you also need to set the day, that's why you can't set the time before the current time of the phone.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
if(calendar.getTimeInMillis() < System.currentTimeMillis())
calendar.add(Calendar.DAY, 1);
https://stackoverflow.com/a/20438452/6873402
I would just like to share this answer that I found about the Delay Problem in the Alarm Clock
I want to create notification daily in my android app. For the purpose I made a createNotification method. Now, I want to call the method at a particular time. My mainactivity.java is as follows:
package com.example.shiza.dailyquranquote;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
Date startDate= new Date("03/31/2015 12:00:00");
Date endDate = new Date();
TextView textView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.verse);
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
long daysBetween = endDay - startDay;
SharedPreferences sharedPreferences = getSharedPreferences("QuranVerse",0);
String id = ""+ (daysBetween % 365) ;
String verse = sharedPreferences.getString(id, "");
if (verse == null)
{
verse ="Sufficient is Allah for me; There is no power except Him; And in Him I put my trust.";
}
Calendar rightNow = Calendar.getInstance();
textView.setText(verse + "current hour is" + rightNow.HOUR_OF_DAY);
if ( rightNow.HOUR_OF_DAY == 11 )
{
createNotification();
}
}
public void goToInsertVerse(View v)
{
Intent intent = new Intent(this,InsertVerse.class);
startActivity(intent);
}
public void goToGetVerse(View v)
{
Intent intent = new Intent(this,GetVerse.class);
startActivity(intent);
}
public void createNotification(View view) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject").setSmallIcon(R.drawable.background)
.setContentIntent(pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
Now I need to pass view as a parameter to createNotification. I am unable to do it. How I can achieve it?
user setContent method wich takes "RemoteViews" as parameter