I have a problem while passing String to a Service from Activity. What I am trying to do is to pass different Strings each time I call Service. I use Intent (putExtra() method each time). The problem is that each time it shows the first String that I passed. Is there a way to implement that?
Here is my Activity, Broadcast Receiver, Service
public class MainActivity extends Activity implements View.OnClickListener{
private PendingIntent pendingIntent;
private EditText event;
private Button submit, date, time;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int myYear = 2014;
private int myMonth = 8;
private int myDay = 16;
private int myHour = 6;
private int myMinute = 30;
private List<String> events;
private List<Calendar> dateTimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
event = (EditText)findViewById(R.id.event);
submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(this);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(this);
time = (Button)findViewById(R.id.time);
time.setOnClickListener(this);
events = new ArrayList<String>();
dateTimes = new ArrayList<Calendar>();
//List<Calendar> events = new ArrayList<Calendar>();
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_DATE) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return datePickerDialog;
}else {
TimePickerDialog timePickerDialog = new TimePickerDialog(this, myCallBack1, myHour, myMinute, true);
return timePickerDialog;
}
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
myYear = year;
myMonth = month;
myDay = day;
}
};
TimePickerDialog.OnTimeSetListener myCallBack1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
myHour = hour;
myMinute = minute;
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.date:
showDialog(DIALOG_DATE);
break;
case R.id.time:
showDialog(DIALOG_TIME);
break;
case R.id.submit:
String eventS = event.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth);
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.DAY_OF_MONTH, myDay);
calendar.set(Calendar.HOUR_OF_DAY, myHour);
calendar.set(Calendar.MINUTE, myMinute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, BR.class);
myIntent.putExtra("event", eventS);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
event.setText("");
break;
}
}
public class BR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
intent.getExtras().getString("event");
myIntent.putExtra("event", intent.getStringExtra("event"));
context.startService(myIntent);
Log.i("myLogs", "BR started");
}
}
public class MyService 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) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
String event = intent.getExtras().getString("event");
Notification notification = new Notification(R.drawable.ic_launcher, "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_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), event, event, pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
A service can't be stopped until it's finish. You have to wait that your current service finish to send other data. You can collect all your strings and send them all together or wait until your background service finish
Related
The user can press three buttons: One will bring up a clock to select the time, another will bring up a calendar to select the date. The third button is to be pressed last, and is meant to send out a notification.
When I press on the last button, I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.Calendar.before(java.lang.Object)' on a null object reference
at com.example.meeldetuletuserakendus.MeeldetuletusActivity.startAlarm(MeeldetuletusActivity.java:105)
Something goes wrong when trying to do the method startAlarm(c).
I know for certain that everything worked perfectly when the code only had a choice to choose a time, but something broke when I coded the date picking part of the code. So the problem probably has something to do with the date.
MeeldetuletusActivity.java:
public class MeeldetuletusActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
String timeText;
TextView textTime;
Button nupp_vali, nupp_katkesta, nupp_kuupaev, nupp_alarm;
Calendar c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meeldetuletus);
nupp_vali = findViewById(R.id.button2);
nupp_katkesta = findViewById(R.id.nupp_katkesta);
nupp_kuupaev = findViewById(R.id.button);
nupp_alarm = findViewById(R.id.button3);
nupp_alarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAlarm(c);
}
});
nupp_vali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
nupp_kuupaev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment kuupaevaValija = new KuupaevaFragment();
kuupaevaValija.show(getSupportFragmentManager(), "date picker");
}
});
nupp_katkesta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
katkestaAlarm();
Toast.makeText(MeeldetuletusActivity.this, "Meeldetuletus unustatud", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pendingIntent);
}
private void katkestaAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
}
Row 105 is:
if (c.before(Calendar.getInstance())) {
KuupaevaFragment.java:
public class KuupaevaFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int aasta = c.get(Calendar.YEAR);
int kuu = c.get(Calendar.MONTH);
int paev = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(),
aasta, kuu, paev);
}
}
TimePickerFragment.java: (This worked perfectly before, I'm only putting this here so you can see what KuupaevaFragment.java is meant to do aswell)
public class TimePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(),
hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
NotificationPublisher.java:
public class NotificationPublisher extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
Notification notification = nb.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
}
}
NotificationHelper.Java:
class NotificationHelper extends ContextWrapper {
public static final String channelID = "channelID";
public static final String channelName = "Channel Name";
private NotificationManager notificationManager;
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID, channelName,
NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
}
return notificationManager;
}
public NotificationCompat.Builder getChannelNotification() {
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("Meeldetuletus")
.setContentText("Teie valitud aeg on käes")
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24);
}
}
Try to reference to the Activity's field c in onTimeSet and onDateSet:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet(DatePicker view, int aasta, int kuu, int paev) {
c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
So instead of Calendar c = Calendar.getInstance(); write c = Calendar.getInstance(); like in the code above.
Or you can try to initialize c property in Activity:
Calendar c = Calendar.getInstance();
and use it to change Calendar's properties, for example in onTimeSet method:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
I am a bit new to android studio, and i am making an app where the user can select the date and time, and it will schedule and alarm to go off at that time. However, when i set the alarm it does not go off. Does anyone know where i went wrong? Or what it is i can change within my code.
CustomDialogClass
public Activity c;
public Dialog d;
public CircleButton CalendarBtn, TimeBtn;
public Button CancelBtn, ProceedBtn;
public TextView CalendarTxt, TimeTxt;
public EditText ReminderTxt;
//FOR CALENDAR
final Calendar myCalendar = Calendar.getInstance();
//FOR CALENDAR
private void updateLabel(TextView edittext) {
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(sdf.format(myCalendar.getTime()));
}
//FOR CALENDAR
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel(CalendarTxt);
}
};
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
CalendarTxt = (TextView) findViewById(R.id.CurrentDateSelect);
TimeTxt = (TextView) findViewById(R.id.CurrentTimeSelect);
CancelBtn = (Button) findViewById(R.id.CancelBtn);
ProceedBtn = (Button) findViewById(R.id.ProceedBtn);
CancelBtn.setOnClickListener(this);
ProceedBtn.setOnClickListener(this);
CalendarBtn = (CircleButton) findViewById(R.id.calendarBtn);
TimeBtn = (CircleButton) findViewById(R.id.timeBtn);
CalendarBtn.setOnClickListener(this);
TimeBtn.setOnClickListener(this);
ReminderTxt = (EditText) findViewById(R.id.ReminderTxt);
}
#Override
public void onClick(View v) {
//On click method for buttons
switch (v.getId()) {
case R.id.calendarBtn:
new DatePickerDialog(getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
case R.id.CancelBtn:
dismiss();
break;
case R.id.timeBtn:
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
TimeTxt.setText(curTime);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
case R.id.ProceedBtn:
String TimeVal = TimeTxt.getText().toString();
String DateVal = CalendarTxt.getText().toString();
String RemindVal = ReminderTxt.getText().toString();
if ((TimeVal + DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + DateVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else {
String FinalAlarmVal = DateVal + " " + " " + TimeVal;
String AlarmHour = TimeVal.substring(0, 2);
String AlarmMins = TimeVal.substring(3, 5);
String AlarmMonth = DateVal.substring(3, 5);
String AlarmDay = DateVal.substring(0, 2);
System.out.println("SEWISINGHVV- "+ Integer.parseInt(AlarmMonth));
AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins), Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
Intent AlarmName = new Intent(getContext(), AlarmReceiver.class);
AlarmName.putExtra("NameOfAlarm", RemindVal);
getContext().startService(AlarmName);
}
break;
default:
break;
}
//dismiss();
//Ends dialog when button is pressed
}
AlarmScheduler
public static final int DAILY_REMINDER_REQUEST_CODE = 100;
public static final String TAG = "AlarmScheduler";
public static void setReminder(Context context, int hour, int min, int day, int month) {
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.MONTH, month);
setcalendar.set(Calendar.DAY_OF_MONTH, day);
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
setcalendar.set(Calendar.MILLISECOND, 0);
// cancel already scheduled reminders
cancelReminder(context, AlarmReceiver.class);
if (setcalendar.before(calendar))
setcalendar.add(Calendar.DATE, 1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context, Class<?> cls) {
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
AlarmReceiver
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
I created a notification to show released movie and today's reminder. I have method for repeating alarm, but the notification only shows up whenever I turn "ON" the alarm by SwitchPreferences. What I want here is to show notifications every single day and every movie's that being release when I just set the alarm to "ON" once. From my case here, I have to set the alarm on and on to get the notifications, but it supposed to call the notifications or request the data when the onReceive() function in BroadcastReceiver() class being called. Summarize, I just want to turn ON the alarm once and then the method will check the data from api if it's match to the date requested every single day
Here is my AppCompatPref.java:
public class AppCompatPref extends PreferenceActivity {
private AppCompatDelegate mAppCompatDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mAppCompatDelegate == null) {
mAppCompatDelegate = AppCompatDelegate.create(this, null);
}
return mAppCompatDelegate;
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
}
Here's my MovieDailyReminder:
public class MovieDailyReceiver extends BroadcastReceiver {
private void sendNotification(Context context, String title, String desc, int id) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(context, MainActivity.class);
PendingIntent mPendingIntent = PendingIntent.getActivity(context, id, mIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri uriTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentTitle(title)
.setContentText(desc)
.setContentIntent(mPendingIntent)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(uriTone);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mNotificationChannel = new NotificationChannel(
"11001", "NOTIFICATION_CHANNEL_NAME",
NotificationManager.IMPORTANCE_HIGH);
mNotificationChannel.enableLights(true);
mNotificationChannel.setLightColor(Color.YELLOW);
mNotificationChannel.enableVibration(true);
mNotificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setChannelId("11001");
mNotificationManager.createNotificationChannel(mNotificationChannel);
}
mNotificationManager.notify(id, builder.build());
}
private static PendingIntent getPendingIntent(Context context) {
Intent mIntent = new Intent(context, MovieDailyReceiver.class);
return PendingIntent.getBroadcast(context, 1001, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public void setAlarm(Context context) {
cancelAlarm(context);
AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY, 7);
mCalendar.set(Calendar.MINUTE, 0);
mCalendar.set(Calendar.SECOND, 0);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,mCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,getPendingIntent(context));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,mCalendar.getTimeInMillis(), getPendingIntent(context));
}
Toast.makeText(context, "Daily Notif ON", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(Context context) {
AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mAlarmManager.cancel(getPendingIntent(context));
Toast.makeText(context, "Daily Notif OFF", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceive(Context context, Intent mIntent) {
sendNotification(context, context.getString(R.string.DailyTitle),
context.getString(R.string.DailyCheck), 1001);
}
}
Here's my MovieUpcomingReminder:
public class MovieUpcomingReceiver extends BroadcastReceiver {
private static int mNotifId = 2000;
private void sendNotification(Context context, String title, String mDesc, int id, ResultsItem mMovieResult) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Uri uriTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentTitle(title)
.setContentText(mDesc)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(uriTone);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("11011",
"NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.YELLOW);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setChannelId("11011");
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, builder.build());
}
private static PendingIntent getPendingIntent(Context context) {
Intent intent = new Intent(context, MovieUpcomingReceiver.class);
return PendingIntent.getBroadcast(context, 1011, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public void setAlarm(Context context, List<ResultsItem> mMovieResults) {
int delay = 0;
for (ResultsItem movie : mMovieResults) {
cancelAlarm(context);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MovieUpcomingReceiver.class);
intent.putExtra("movietitle", movie.getTitle());
intent.putExtra("movieid", movie.getId());
intent.putExtra("movieposter", movie.getPhoto());
intent.putExtra("moviemDescription", movie.getOverview());
intent.putExtra("moviedate", movie.getReleaseDate());
intent.putExtra("id", mNotifId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis() + delay,
AlarmManager.INTERVAL_DAY,
pendingIntent
);
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis() + delay, pendingIntent);
}
mNotifId += 1;
delay += 3000;
}
Toast.makeText(context, "Upcoming Notif ON", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceive(Context context, Intent intent) {
String mMovieTitle = intent.getStringExtra("movietitle");
int id = intent.getIntExtra("id", 0);
ResultsItem mMovieResult = new ResultsItem();
String mDesc = context.getString(R.string.todayRelease) + " : " +mMovieTitle;
sendNotification(context, context.getString(R.string.app_name), mDesc, id, mMovieResult);
}
public void cancelAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(getPendingIntent(context));
Toast.makeText(context, "Upcoming Notif OFF", Toast.LENGTH_SHORT).show();
}
}
Here's my SettingPref:
public class SettingPref extends AppCompatPref {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public static class MainPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
private RequestQueue mRequestQueue;
List<ResultsItem> mNotifList;
MovieDailyReceiver mMovieDailyReceiver = new MovieDailyReceiver();
MovieUpcomingReceiver mMovieUpcomingReceiver = new MovieUpcomingReceiver();
SwitchPreference mSwitchReminder;
SwitchPreference mSwitchToday;
public class GetMovieTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
getData(strings[0]);
return null;
}
}
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
boolean value = (boolean) newValue;
if (key.equals(getString(R.string.todayreminder))) {
if (value) {
mMovieDailyReceiver.setAlarm(getActivity());
} else {
mMovieDailyReceiver.cancelAlarm(getActivity());
}
} else {
if (value) {
setReleaseAlarm();
} else {
mMovieUpcomingReceiver.cancelAlarm(getActivity());
}
}
return true;
}
private void setReleaseAlarm() {
Date today = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String todaysDate = dateFormat.format(today);
MainPreferenceFragment.GetMovieTask getDataAsync = new MainPreferenceFragment.GetMovieTask();
getDataAsync.execute("https://api.themoviedb.org/3/discover/movie?api_key=80077c53d53b7215a6c2f2120d065f81&primary_release_date.gte="+todaysDate+"&primary_release_date.lte="+todaysDate);
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mNotifList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(getActivity());
mSwitchReminder = (SwitchPreference) findPreference(getString(R.string.todayreminder));
mSwitchReminder.setOnPreferenceChangeListener(this);
mSwitchToday = (SwitchPreference) findPreference(getString(R.string.todayRelease));
mSwitchToday.setOnPreferenceChangeListener(this);
Preference myPref = findPreference(getString(R.string.languagesets));
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
startActivity(new Intent(Settings.ACTION_LOCALE_SETTINGS));
return true;
}
});
}
public void getData(String url) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
final String today = dateFormat.format(date);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
ResultsItem movieItem = new ResultsItem();
movieItem.setTitle(data.getString("title"));
movieItem.setReleaseDate(data.getString("release_date"));
movieItem.setTitle(data.getString("title"));
movieItem.setOverview(data.getString("overview"));
movieItem.setOverview(data.getString("poster_path"));
if (data.getString("release_date").equals(today)) {
mNotifList.add(movieItem);
}
}
mMovieUpcomingReceiver.setAlarm(getActivity(), mNotifList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
}
}
I am working on an app that reminds the user of an event at a particular date and time. I am having problem using the broadcast receiver. Suppose the user clicks on item 0, then position of the item is 0. I check if the position does equal to 0, then set the specific date and time for the notification. Then receiver class will call the message class to show the message. Based on my code, the receiver method should show three different notification because each has a different id but this is not happening. Only the first notification is shown.
In MyReceiver I want to have the position variable from arrayadapter that keeps tracks of what item was clicked. But I am not able to do that (at onItemClick)
I have more than 94 events, and I don't want to have 94 Broadcast receiver classes to show me the notification for each event. Is THERE ANY WAY I CAN USE ONE RECEIVER CLASS TO SHOW ALL THE NOTIFICATIONS.
I tested it out by having separate Broadcast receiver class for each event and it worked fine.
This is what I did:
1.I created three different receiver classes
2.In the message class, I have methods for each notification
3. and in each receiver class I called the specific method like this
Message nm = new Message();
nm.generateNotification(context);
and the main class I did this:
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
MyReceiver in this case is one of the three receiver classes I implemented.
Could someone please tell me how I can say that if(position ==0) show this notification and so on.
This is my Main class.
public class BuddhaEvent extends AppCompatActivity implements View.OnClickListener {
public List<list> myList = new ArrayList<list>();
private PendingIntent pendingIntent;
android.support.v4.app.NotificationCompat.Builder notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_buddhism_event);
fill_eventsList();
fill_ListView();
clickResponse();
Button buddah_button_event = (Button) findViewById(R.id.button_event_back_buddhism);
buddah_button_event.setOnClickListener(this);
}
// public list(String date, int iconId, String details, String name) {
private void fill_eventsList() {
myList.add(new list("Jan-24", R.drawable.chris, "Mahayana countries the new year starts on the first full moon day in January.", "Mahayana New Year"));
myList.add(new list("Feb-2", R.drawable.chris, "Chinese festival celebrated at the turn of the traditional lunisolar Chinese calendar.", "Chinese New Year"));
myList.add(new list("Feb-15", R.drawable.chris, "Celebrates the day when the Buddha is said to have achieved Parinirvana, or complete Nirvana", "Nirvana Day"));
myList.add(new list("Mar-23", R.drawable.chris, "Celebration in honour of the Sangha, or the Buddhist community", "Magha Puja Day"));
myList.add(new list("Apr-22", R.drawable.chris, "Buddhist New Year", "Theravada New Year"));
myList.add(new list("May-15", R.drawable.chris, "Celebrates the Buddha's birthday", "Wesak - Buddha Day"));
myList.add(new list("Jul-11", R.drawable.chris, "Honor the spirits of one's ancestors.", "Obon"));
myList.add(new list("Jul-19", R.drawable.chris, "Celebrates Buddha's teachings of peace and enlightenment", "Asala - Dharma Day"));
myList.add(new list("Dec-8", R.drawable.chris, "The day that the historical Buddha, Siddhartha Gautama (Shakyamuni), experienced enlightenment", "Bodhi Day"));
}
private void fill_ListView() {
ArrayAdapter<list> listArrayAdapter = new myListAdapter();
ListView list = (ListView) findViewById(R.id.list_eventsView);
list.setAdapter(listArrayAdapter);
}
public void clickResponse() {
ListView l = (ListView) findViewById(R.id.list_eventsView);
if (l != null) {
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View viewClicked,
final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(
BuddhaEvent.this);
alert.setTitle("Reminder!!");
alert.setMessage("Do you want to be reminded of this event in future?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (position == 0) {
Calendar calendar = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar.set(Calendar.MONTH, 6);
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 18);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 50);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 45454, myIntent, 0);
AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
if (position == 1) {
Calendar calendar2 = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar2.set(Calendar.MONTH, 6);
calendar2.set(Calendar.YEAR, 2016);
calendar2.set(Calendar.DAY_OF_MONTH, 18);
calendar2.set(Calendar.HOUR_OF_DAY, 15);
calendar2.set(Calendar.MINUTE, 51);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.AM_PM, Calendar.PM);
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 12322, myInten2t, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent);
}
if (position == 2) {
counter++;
Calendar calendar2 = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar2.set(Calendar.MONTH, 6);
calendar2.set(Calendar.YEAR, 2016);
calendar2.set(Calendar.DAY_OF_MONTH, 18);
calendar2.set(Calendar.HOUR_OF_DAY, 15);
calendar2.set(Calendar.MINUTE, 52);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.AM_PM, Calendar.PM);
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 12322, myInten2t, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent);
}
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
}
}
private class myListAdapter extends ArrayAdapter<list> {
public myListAdapter() {
// what objects are going in there and how are they going to look
super(BuddhaEvent.this, R.layout.custom_events_layout, myList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.custom_events_layout, parent, false);
}
list current_list = myList.get(position);
ImageView imageView = (ImageView) itemView.findViewById(R.id.id_image);
imageView.setImageResource(current_list.getIconId());
TextView titleTxt = (TextView) itemView.findViewById(R.id.id_event);
titleTxt.setText(current_list.getName());
EditText text = (EditText) itemView.findViewById(R.id.id_desp);
text.setText(current_list.getDetails());
TextView date = (TextView) itemView.findViewById(R.id.id_date);
date.setText(current_list.getDate());
return itemView;
}
}
public void onClick(View v) {
startActivity(new Intent(BuddhaEvent.this, BuddhaScreen.class));
}
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
BuddhaEvent check = new BuddhaEvent();
Log.i("App", "called receiver method");
try {
Message nm = new Message();
nm.generateNotification(context);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my message class
public class Message {
#SuppressWarnings("static-access")
public void generateNotification(Context context) {
Intent intent = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification;
notification = new NotificationCompat.Builder(context);
notification.setAutoCancel(true);
notification.setSmallIcon(R.drawable.ic_launcher);
notification.setTicker("This is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Title");
notification.setContentText("Hello this is the description");
PendingIntent pendingIntent = PendingIntent.getActivity(context,1, intent, 0);
notification.setContentIntent(pendingIntent);
NotificationManager nm1 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm1.notify(1, notification.build());
}
public void generateNotification2(Context context) {
Intent intent2 = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification2;
notification2 = new NotificationCompat.Builder(context);
notification2.setAutoCancel(true);
notification2.setSmallIcon(R.drawable.ic_launcher);
notification2.setTicker("This is the ticker2");
notification2.setWhen(System.currentTimeMillis());
notification2.setContentTitle("second title");
notification2.setContentText("I am the body");
PendingIntent pendingIntent2 = PendingIntent.getActivity(context,2, intent2, 0);
notification2.setContentIntent(pendingIntent2);
NotificationManager nm2 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm2.notify(2, notification2.build());
}
public void generateNotification3(Context context) {
Intent intent2 = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification2;
notification2 = new NotificationCompat.Builder(context);
notification2.setAutoCancel(true);
notification2.setSmallIcon(R.drawable.ic_launcher);
notification2.setTicker("This is the ticker3");
notification2.setWhen(System.currentTimeMillis());
notification2.setContentTitle("third title");
notification2.setContentText("I am the body");
PendingIntent pendingIntent2 = PendingIntent.getActivity(context,3, intent2, 0);
notification2.setContentIntent(pendingIntent2);
NotificationManager nm2 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm2.notify(3, notification2.build());
}
}
i am trying to send Message at a scheduled time in my app
here is my activty
public class Lenditem extends Activity {
Context mContext;
private int mHour;
private int mMin;
private int mYear;
private int mMonth;
private int mDay;
Button b1, b2, b3;
EditText et1, et2,et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Full screen code
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lenditem);
b1 = (Button)findViewById(R.id.bselectcontactlenditem);
b3 = (Button)findViewById(R.id.bcancellenditem);
et1 = (EditText)findViewById(R.id.etdesclenditem);
et2 = (EditText)findViewById(R.id.etamountlenditem);
et3 = (EditText)findViewById(R.id.lietentercontact);
Button dateSet=(Button) findViewById(R.id.limyDatePickerButton);
Button timeSet=(Button) findViewById(R.id.limyTimePickerButton);
b3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
boolean diditWork = true;
try {
String Desc1 = et1.getText().toString();
String Amt1 = et2.getText().toString();
Databaselentitem entry = new Databaselentitem(Lenditem.this);
entry.open();
entry.createEntry1(Desc1, Amt1);
entry.close();
} catch (Exception e) {
diditWork = false;
Toast.makeText(getApplicationContext(), "Something's Wrong.!!", Toast.LENGTH_LONG).show();
} finally {
if (diditWork) {
Toast.makeText(getApplicationContext(), "Reminder saved successfully.!!", Toast.LENGTH_LONG).show();
}
}
}
});
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// user BoD suggests using Intent.ACTION_PICK instead of
// .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
dateSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent localIntent1 = new Intent();
localIntent1.setClass(Lenditem.this.mContext, TimePickerActivity.class);
Lenditem.this.startActivityForResult(localIntent1, 0);
return;
/* DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
mMonth=monthofyear;
mYear=year;
mDay=dayofmonth;
Toast.makeText(getBaseContext(), "Date Set is :"+mDay+"/"+(mMonth+1)+"/"+mYear, Toast.LENGTH_SHORT).show();
}
};
// TODO Auto-generated method stub
new DatePickerDialog(Lenditem.this,d,Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH).show();
*/ }
});
timeSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view2, int hour, int min) {
// TODO Auto-generated method stub
mHour = hour;
mMin = min;
if (mHour >= 12)
mHour = mHour - 12;
Log.d("MYAPP", "hh:" + mHour + "\nmm:" + mMin);
Toast.makeText(getBaseContext(),
"Time Set is:" + mHour + ":" + mMin + ":00",
Toast.LENGTH_SHORT).show();
}
};
Calendar cal = Calendar.getInstance();
new TimePickerDialog(Lenditem.this, t, cal
.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
true).show();
}
});
Button saveAndClearBtn = (Button) findViewById(R.id.bSubmitlenditem);
saveAndClearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar myCal = Calendar.getInstance();
long timeToTrigger;
myCal.set(Calendar.YEAR, mYear);
myCal.set(Calendar.MONTH, mMonth);
myCal.set(Calendar.DAY_OF_MONTH, mDay);
myCal.set(Calendar.HOUR, mHour);
myCal.set(Calendar.MINUTE, mMin);
myCal.set(Calendar.SECOND, 0);
long setTime = myCal.getTimeInMillis();
if (setTime > System.currentTimeMillis()) {
timeToTrigger = setTime - System.currentTimeMillis();
EditText edt1 = (EditText) findViewById(R.id.bselectcontactlenditem);
EditText edt2 = (EditText) findViewById(R.id.litxtMessage);
String msg = edt2.getText().toString();
String telno = edt1.getText().toString();
int count = 0;
SQLiteDatabase db = openOrCreateDatabase("MYDBli",
MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS mySmsSchedulerli(SlNo VARCHAR,Number VARCHAR,Msg VARCHAR);");
String s = "INSERT INTO mySmsSchedulerli VALUES ('" + count
+ "','" + telno + "','" + msg + "');";
db.execSQL(s);
Log.d("MYREC", "Insertion of data successfull");
db.close();
edt1.setText("");
edt2.setText("");
Intent intent = new Intent();
intent.setClass(Lenditem.this, MyBroadcastRecieverli.class);
Bundle b = new Bundle();
b.putString("index", Integer.toString(count));
intent.putExtras(b);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Lenditem.this, (int) Math.random(), intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + timeToTrigger,
pendingIntent);
count++;
Toast.makeText(
getBaseContext(),
"Sms Scheduled after:" + (timeToTrigger / (1000*60*60))+" Hours "+(timeToTrigger/(1000*60))+" Minutes "
+(timeToTrigger/1000)+ " sec.", Toast.LENGTH_SHORT).show();
Log.d("MYAPP", "Set Time:" + (setTime / 1000) + "Sec. \n"
+ "Cur time:" + System.currentTimeMillis() / 1000);
Log.d("MYAPP", "Time to trigger:" + (timeToTrigger / 1000)
+ "sec.");
} else {
Toast.makeText(getBaseContext(),
"Please Enter a valid time", Toast.LENGTH_SHORT)
.show();
Calendar calendar = Calendar.getInstance();
int h = calendar.get(Calendar.HOUR);
int m = calendar.get(Calendar.MINUTE);
Log.d("MYAPP", "cur HH:" + h + "\ncur MM:" + m);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
et3.setText(number);
}
}
this is broadcast class
public class MyBroadcastRecieverli extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int myCount;
String cnt=intent.getStringExtra("index");
if(cnt==null)
Log.d("MYAPP","Data not received");
Log.d("MYAPP", "Count:"+cnt);
myCount=Integer.parseInt(cnt);
Log.d("MYAPP","Broadcast receiver called...");
SQLiteDatabase db=arg0.openOrCreateDatabase("MYDB",Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT Number, Msg FROM mySmsSchedulerli WHERE SlNo=="+myCount, null);
Log.d("MYAPP", "Cursor reference obtained...");
if(c!=null)
{
c.moveToFirst();
}
else
Log.d("MYAPP", "cursor is null");
/* c.moveToFirst();*/
String num=c.getString(c.getColumnIndex("Number"));
String myMsg=c.getString(c.getColumnIndex("Msg"));
Log.d("MYAPP", "number:"+num+"\nMsg:"+myMsg);
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(num, null, myMsg, null, null);
Log.d("MYAPP", "Message Sent");
Toast.makeText(arg0, "Msg sent successfully", Toast.LENGTH_LONG).show();
String table="mySmsSchedulerli";
String whereClause = "SlNo = ?";
String[] whereArgs = new String[] { Integer.toString(Sms.count) };
db.delete(table, whereClause, whereArgs);
db.close();
Log.d("MYAPP", "Entry deleted..");
}
}
it is showing the toast that your msg will be send after xxxx seconds but not sending msg at scheduled time.
can anybody help me plzzz
Try to use Broadcast Receive first and then start a service.
Something like that:
create a function:
public static void setRecurringAlarm(Context context, Class<?> cls, int time, int minute) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
updateTime.set(Calendar.HOUR_OF_DAY, time);
updateTime.set(Calendar.MINUTE, minute);
Intent alarm = new Intent(context, cls);
PendingIntent recurringAlarm = PendingIntent.getBroadcast(context, 654789, alarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringAlarm);
}
If you don't want to set a recurring alarm, just change setRepeating to set.
In your code, you need to call:
// to start the receiver at 9:00am
setRecurringAlarm(this, AlarmManagerReceiver.class, 9, 0);
So, you need to create the AlarmManagerReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmManagerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent alarmService = new Intent(context, AlarmManagerService.class);
context.startService(alarmService);
}
}
And now, you need the service:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
public class AlarmManagerService extends Service {
private Context context;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = this.getApplicationContext();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// Do what you need to do.
stopSelf();
}
}
In manifest:
<receiver android:name=".AlarmManagerReceiver" >
<intent-filter>
<action android:name=".AlarmManagerReceiver" />
</intent-filter>
</receiver>
<service
android:name=".AlarmManagerService"
android:enabled="true" >
<intent-filter>
<action android:name=".AlarmManagerService" />
</intent-filter>
</service>