No message shows up - Notification - java

I am trying to set a Alarm. The user selects a time with the time picker and when time comes a Notification shows up. This works perfectly. But the problem is, the User Input the name of the alarm the user wrote doesn't show up. I do NOT get a error message!
https://prnt.sc/mfs5hx
https://prnt.sc/mfs5w2
NotificationHelper.java:
public NotificationCompat.Builder getChannelNotification() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View frAl = inflater.inflate(R.layout.fragment_alarm, null);
titelAlarm = frAl.findViewById(R.id.eingUserAlarm);
String nameAlarm = titelAlarm.getText().toString();
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("Erinnerung")
.setContentText(nameAlarm)
.setSmallIcon(R.drawable.ic_one);
}
The EditText where the user can name the Alarm is inside a Fragment which can be accessed by a Navigation Drawer.
<EditText
android:id="#+id/eingUserAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:hint="Was wirst du machen?" />
Also the code for the Alarm is inside my Fragment.java.
Fragment.java:
Button buttonTimePicker = fraAla.findViewById(R.id.button_timepicker);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new AlarmTimePicker();
timePicker.show(getChildFragmentManager(), "time picker");
}
});
Button buttonCancelAlarm = fraAla.findViewById(R.id.button_cancel);
buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancelAlarm();
}
});
return fraAla;
}
#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);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Wir erinnern dich um ";
timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
mTextView.setText(timeText);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Wir werden nicht stören!");
}

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.Calendar.before(java.lang.Object)' on a null object reference

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);
}

Cannot send daily notfication on android with java

I'm trying 1 month now to make a feature witch sends to the user one notification daily at the time the user has selected but when the onTimeSet() called i'm getting only this error below and the Notification is not coming to the user
I try these solutions below:
removing all code from onTimeSet() & startAlarm() inside my activity
changing this to SetNotificationActivity.this
Invalidate chaches / restart
Error:
E/InputDispatcher: Window handle Window{838da5a u0 com.george.igrow/com.george.igrow.SetNotificationActivity} has no registered input channel
SetNotificationActivity.java:
public class SetNotificationActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notification);
final Button setAlarm = findViewById(R.id.buttonAlarm);
final Button skip_btn = findViewById(R.id.button4);
setAlarm.setOnClickListener(v -> {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
});
skip_btn.setOnClickListener(v -> {
finish();
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
});
}
#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);
startAlarm(c);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance()))
c.add(Calendar.DATE, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
}
}
AlertReceiver.java:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SplashScreenActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Send notification for the current Alarm
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
//nb.setContentIntent(pendingIntent);
notificationHelper.getManager().notify(1, nb.build());
}
}

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());

One Broadcast receiver for multiple notifications Android studio

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());
}
}

How to send sms frequently like these(daily, weekly, every 5 minutes, every hour)

I want to send sms frequently like that in question; I am using spinner option with some option like that(daily,weekly,every 5 minutes),while i select any option in these spinner it has to go like that.
Alaramsms.java:
private String[] Time_CATEGORY = { "Once","Every hour","Every day", "Weekdays(Mon-Fri)", "Weekend", "Every month",
"Every year" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextSmsNumber = (EditText)findViewById(R.id.smsnumber);
edittextSmsText = (EditText)findViewById(R.id.smstext);
ImageButton get = (ImageButton)findViewById(R.id.getc);
spinnerTime = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Time_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Button buttonStart = (Button)findViewById(R.id.startalarm);
Button buttonCancel = (Button)findViewById(R.id.cancelalarm);
spinnerTime.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinnerTime.setSelection(position);
//spinnerCapital.setSelection(position);
String myPrayer = (String) spinnerTime.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}});
get.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AndroidAlarmSMS.this, ContactActivity.class);
startActivityForResult(i, ResultCode);
}
});
buttonStart.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
smsNumber = edittextSmsNumber.getText().toString();
smsText = edittextSmsText.getText().toString();
picker = new Dialog(AndroidAlarmSMS.this);
picker.setContentView(R.layout.picker_frag);
picker.setTitle("Select Date and Time");
datep = (DatePicker)picker.findViewById(R.id.datePicker);
timep = (TimePicker)picker.findViewById(R.id.timePicker1);
set = (Button)picker.findViewById(R.id.btnSet);
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(smsNumber))
{
finish();
}
else
{
String[] s =edittextSmsNumber.getText().toString().split(";");
for(int i=0 ;i<s.length;i++)
{
picker.dismiss();
Intent myIntent = new Intent(AndroidAlarmSMS.this, MyAlarmService.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("extraSmsNumber", smsNumber);
bundle.putCharSequence("extraSmsText", smsText);
myIntent.putExtras(bundle);
pendingIntent = PendingIntent.getService(AndroidAlarmSMS.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
// long startTime = calendar.getTimeInMillis();
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.SECOND, 60);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(AndroidAlarmSMS.this,
"Start Alarm with \n" +
"smsNumber = " + smsNumber + "\n" +
"smsText = " + smsText,
Toast.LENGTH_LONG).show();
}
}
}
});
picker.show();
}});
buttonCancel.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Toast.makeText(AndroidAlarmSMS.this, "Cancel!", Toast.LENGTH_LONG).show();
}});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if(resultCode == RESULT_OK){
sendlist =data.getStringArrayListExtra("name");
if(sendlist!=null)
{
for(int i=0;i<sendlist.size();i++)
{
edittextSmsNumber.append(sendlist.get(i).toString());
edittextSmsNumber.append(";");
}
}
if (resultCode == RESULT_CANCELED) {
}
}
}
}
Now I am sending sms using scheduling time; it is going now at what user select the time.But i want to send sms According to spinner selection.
You need to use setInexactRepeating method
For example, to set alarm "Every Day" :
alarmMgr0 .setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, intent);
This is your AndroidAlarmSMS.Java file.
private String[] Time_CATEGORY = { "Once", "Every 5 Minutes", "Every hour",
"Every day", "Weekly", "Weekdays(Mon-Fri)", "Weekend",
"Every month", "Every year" };
EditText edittextSmsNumber, edittextSmsText;
String smsNumber, smsText;
Dialog picker;
Button select;
Button set;
String mytime;
ImageButton get;
TimePicker timep;
DatePicker datep;
Integer hour, minute, month, day, year, week;
TextView time, date;
private PendingIntent pendingIntent;
static int ResultCode = 12;
ArrayList<String> sendlist = new ArrayList<String>();
Spinner spinnerTime;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextSmsNumber = (EditText) findViewById(R.id.smsnumber);
edittextSmsText = (EditText) findViewById(R.id.smstext);
ImageButton get = (ImageButton) findViewById(R.id.getc);
datep = (DatePicker) findViewById(R.id.datePicker);
timep = (TimePicker) findViewById(R.id.timePicker1);
Button buttonStart = (Button) findViewById(R.id.startalarm);
Button buttonCancel = (Button) findViewById(R.id.cancelalarm);
spinnerTime = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Time_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTime.setAdapter(adapter_state);
spinnerTime.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
spinnerTime.setSelection(position);
// spinnerCapital.setSelection(position);
mytime = (String) spinnerTime.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
get.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AndroidAlarmSMS.this,
ContactActivity.class);
startActivityForResult(i, ResultCode);
}
});
buttonStart.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
smsNumber = edittextSmsNumber.getText().toString();
smsText = edittextSmsText.getText().toString();
// picker = new Dialog(AndroidAlarmSMS.this);
// picker.setContentView(R.layout.picker_frag);
// picker.setTitle("Select Date and Time");
// set = (Button)picker.findViewById(R.id.btnSet);
// set.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
if (TextUtils.isEmpty(smsNumber)) {
finish();
}
else {
String[] s = edittextSmsNumber.getText().toString()
.split(";");
for (int i = 0; i < s.length; i++) {
// picker.dismiss();
Intent myIntent = new Intent(AndroidAlarmSMS.this,
MyAlarmService.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("extraSmsNumber", smsNumber);
bundle.putCharSequence("extraSmsText", smsText);
myIntent.putExtras(bundle);
pendingIntent = PendingIntent.getService(
AndroidAlarmSMS.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// long startTime = calendar.getTimeInMillis();
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.SECOND, 60);
if (mytime.equals("Once")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
} else if (mytime.equals("Every 5 Minutes")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 5,
pendingIntent); // Millisec * Second *
// Minute
} else if (mytime.equals("Every hour")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 60,
pendingIntent); // Millisec * Second *
// Minute
} else if (mytime.equals("Every day")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
24 * 60 * 60 * 1000, pendingIntent);
} else if (mytime.equals("Weekly")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 7 * 24 * 60
* 60 * 1000, pendingIntent);
} else if (mytime.equals("Weekdays(Mon-Fri)")) {
forWeekdays();
} else if (mytime.equals("Weekend")) {
forWeekend();
} else if (mytime.equals("Every month")) {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 30 * 24 * 60
* 60 * 1000, pendingIntent);
} else {
Calendar calendar = Calendar.getInstance();
calendar.set(datep.getYear(), datep.getMonth(),
datep.getDayOfMonth(),
timep.getCurrentHour(),
timep.getCurrentMinute(), 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 365 * 24 * 60
* 60 * 1000, pendingIntent);
}
Toast.makeText(
AndroidAlarmSMS.this,
"Start Alarm with \n" + "smsNumber = "
+ smsNumber + "\n" + "smsText = "
+ smsText, Toast.LENGTH_LONG).show();
}
}
}
});
// picker.show();
// }});
buttonCancel.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Toast.makeText(AndroidAlarmSMS.this, "Cancel!",
Toast.LENGTH_LONG).show();
}
});
}
public void forWeekdays() {
Calendar calendar2 = Calendar.getInstance();
calendar2.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
int day = calendar2.get(Calendar.DAY_OF_WEEK);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (day == 2 || day == 3 || day == 4 || day == 5 || day == 6) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar2.getTimeInMillis(), 24 * 60 * 60 * 1000,
pendingIntent);
}
}
public void forWeekend() {
Calendar calendar2 = Calendar.getInstance();
calendar2.set(datep.getYear(), datep.getMonth(), datep.getDayOfMonth(),
timep.getCurrentHour(), timep.getCurrentMinute(), 0);
int day = calendar2.get(Calendar.DAY_OF_WEEK);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (day == 1 || day == 7) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar2.getTimeInMillis(), 24 * 60 * 60 * 1000,
pendingIntent);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
sendlist = data.getStringArrayListExtra("name");
if (sendlist != null) {
for (int i = 0; i < sendlist.size(); i++) {
edittextSmsNumber.append(sendlist.get(i).toString());
edittextSmsNumber.append(";");
}
}
if (resultCode == RESULT_CANCELED) {
}
}
}
instead of using alarmManager.set(), you can use alarmManager.setRepeating() to repeat the task..
You have to use setRepeating() mmethod of AlarmManager to have this achieved.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeat_interval, pendingIntent);
In the above piece of code you've to replace the value of 'repeat_interval' as per your selection i.e., daily,weekly,every 5 minutes. It denotes the interval at which the alarm repeats. But you've to pass those values in milliseconds.

Categories