can anyone help me with a normal alarm clock app that uses TimePicker to set the time ..and also uses intents,etc instead of normal comparisons.This is the code that i've done till now.But this is not working. The 'TimePicker' sets the time and on pressing the 'ToggleButton' a 'TextVew' shows that alarm is on .But when the alarmtime is reached,Alarm Ringing message is not shown.Please someone help me out.
this is the code of main activity
public class FullscreenActivity extends Activity implements OnClickListener {
TimePicker TimePickerForGettingTime;
TextView AlarmSet;
TextView AlarmOnOff;
ToggleButton ConfirmButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
TimePickerForGettingTime= (TimePicker)findViewById(R.id.TimePickerForGettingTime);
ConfirmButton = (ToggleButton) findViewById(R.id.ConfirmButton);
ConfirmButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{ boolean on=((ToggleButton) v).isChecked() ;
AlarmOnOff=(TextView)findViewById(R.id.AlarmOnOff);
if(on)
{
AlarmOnOff.setText("Alarm on");
Calendar cal = Calendar.getInstance();
cal.set(TimePickerForGettingTime.getCurrentHour(),TimePickerForGettingTime.getCurrentMinute(),00);
setAlarm(cal);
}
else
{
AlarmOnOff.setText("Alarm off");
}
}
});
}
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(FullscreenActivity.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(FullscreenActivity.this, 0, alarmintent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
this is the onbootreceiver class
public class OnBootReceiver extends BroadcastReceiver {
private static final int PERIOD=10000; // 10sec
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
}
}
this is the alarmreceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
NotificationManager manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
Notification noti = new Notification(android.R.drawable.stat_notify_more, "Wake up alarm", System.currentTimeMillis());
noti.setLatestEventInfo(context, "My Alarm", "WAKE UP...!!!", sender);
noti.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(R.string.app_name, noti);
//intent to call the activity which shows on ringing
Intent myIntent = new Intent(context, FullscreenActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
//display that alarm is ringing
Toast.makeText(context, "Alarm Ringing...!!!", Toast.LENGTH_LONG).show();
}
}
Have you registered the alarm receiver in you manifest ?
You should have this in your manifest.
<application>
.
.
.
<receiver android:name=".AlarmReceiver" android:process=":remote" />
</application>
Also, I am not sure that is the right way to calendar set, but I could be wrong . I do it like this and it works fine for me
Calendar cal = Calendar.getInstance();
cal.set (Calendar.HOUR_OF_DAY, time_picker.getCurrentHour());
cal.set (Calendar.MINUTE, time_picker.getCurrentMinute());
Related
I am having trouble to stop the alarm from ringing even after I have pressed the stopAlarm button. thank you for any help.
This is my start alarm switch in MainActivity java class.
public void switchClicked (View view) {
if (((Switch) view).isChecked()) {
Log.d("MainActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
setAlarmText("ON");
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("OFF");
Log.d("MainActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
Here is my StopAlarm button in MainActivity java class.
public void stopAlarm(View view) {
setAlarmText("Alarm stopped");
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
This is the AlarmReciver java class.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
MainActivity inst = MainActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
The problem is in this line
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You are using getService() but you should use getBroadcast() instead.
Why?
getService() retrieves a PendingIntent that will start a service, but since you are using a BroadcastReceiver you should use getBroadcast() that retrieves a PendingIntent that will perform a broadcast.
This application allows me to start a service to remind me drinking. If i click the notification i want to see if the service is running or not, but i don't get any output with the Intent.putExtra method.
My MainActivity class:
Boolean isServiceRunning = false;
AlarmManager alarmManager;
PendingIntent pendingIntent;
TextView mainText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainText = findViewById(R.id.mainTextView);
Bundle extras = getIntent().getExtras();
if (extras == null) {
mainText.setText("Service is paused");
} else {
mainText.setText("Service is running");
}
}
public void sendNotification(View view) {
if (!isServiceRunning) {
isServiceRunning = true;
Toast.makeText(this, "Reminder service started.", Toast.LENGTH_SHORT).show();
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mainText.setText("Service is running.");
Intent i = new Intent(this, reciever.class);
i.putExtra("isServiceRunning", isServiceRunning.booleanValue());
pendingIntent = PendingIntent.getBroadcast(this, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pendingIntent);
} else {
isServiceRunning = false;
Toast.makeText(this, "Reminder service ended.", Toast.LENGTH_SHORT).show();
mainText.setText("Service paused.");
alarmManager.cancel(pendingIntent);
}
}
I think its possible to solve this problem with sharedpreferences, but this shouldn't be a good resolution.
EDIT:
My broadcast reciever class:
public class reciever BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, drinkReminder.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(drinkReminder.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(100, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context, CHANNEL_1_ID)
.setContentTitle("Title")
.setContentText("description")
.setSmallIcon(R.drawable.icon_waterdrop)
.setTimeoutAfter(30000)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, notification);
}
}
You are adding the "extra" to the Intent that you pass to AlarmManager. This "extra" will be in the Intent that gets delivered to your BroadcastReceiver in onReceive(), but you don't do anything with it there.
When you click on the Notification, it will launch drinkReminder, which I hope is an Activity.
You also said in a comment:
Could you tell me please one more thing. Sometimes if i press the
button to start the service, a notification appers after about 10
seconds, after this it shows all 10 minutes like it should. How can i
fix this?
Here is your code for setting the alarm:
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 10, pendingIntent);
When you call setRepeating(), the 2nd parameter specifies the first time the alarm should go off, and the 3rd parameter specifies the repeat interval. You've told alarm manager that you want the first alarm to trigger immediately and then every 10 minutes after that.
If you want the first alarm to trigger 10 minutes after you press the button, you need to adjust the second parameter so it represents a time that is 10 minutes in the future, like this:
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis() + (1000 * 60 * 10), 1000 * 60 * 10, pendingIntent);
Instead of the code in onCreate() and putExtra() ,you can create two pending intents in each case and each intent uses a different broadcast receiver. In that broadcast receiver you can print the separate toast messages.
MyBroadcastRecieverStart.java
public class MyBroadcastReceiverStart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(this, "Reminder service started.", Toast.LENGTH_SHORT).show();
}
}
MyBroadcastReceiverStop.java
public class MyBroadcastReceiverStop extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(this, "Reminder service ended.", Toast.LENGTH_SHORT).show();
}
}
SendNotification method -
public void sendNotification(View view) {
if (!isServiceRunning) {
isServiceRunning = true;
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mainText.setText("Service is running.");
Intent i = new Intent(this, MyBroadcastReceiverStart.class);
pendingIntent = PendingIntent.getBroadcast(this, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pendingIntent);
} else {
isServiceRunning = false;
mainText.setText("Service paused.");
Intent i = new Intent(this, MyBroadcastReceiverStop.class);
pendingIntent = PendingIntent.getBroadcast(this, 100, i, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pendingIntent);
alarmManager.cancel(pendingIntent);
}
}
If you write alarmManager.cancel(pendingIntent) in else block , it is cancelling an intent which does not exist as you have created the intent in if block and it does not get created if else gets executed , so I have created the intent in else block also.
Hi i am making a habit tracker app and when a new habit is created by user i call sendNotification() method for calling notifications at time specified by user.I want to show these notifications everyday at time specified by user.
Now notifications are showing up when app is running or when app is minimized but when i close app (not from settings) notifications are shown.
Here's my code:
private void sendNotification(){
NotificationReceiver.setupAlarm(this, notificationCalendar);
}
public class NotificationReceiver extends WakefulBroadcastReceiver {
public NotificationReceiver() {
}
public static void setupAlarm(Context context, Calendar notificationCalendar) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
startWakefulService(context, serviceIntent);
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationReceiver.class);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
return new Intent(context, NotificationIntentService.class);
}
#Override
protected void onHandleIntent(Intent intent) {
try{
processStartNotification();
}finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Habit Time")
.setContentText("Hey time for your habit")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(alarmSound)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
}
}
//Manifest file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".notification.NotificationReceiver"/>
<service
android:name=".notification.NotificationIntentService"
android:enabled="true"
android:exported="false"/>
The notification won't show until you make a background service for them. Create a background service and send broadcast from that service, this service will keep running weather your app is running or not. You can check this detailed answer.
Make a NotificationService class and extend it like below.
public class NotificationService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
/* send your notification from here, in timely manner */
}
}
Start is from your activity like this
Intent i = new Intent("com.example.package.NotificationService");
startService(i);
This code is written to give you an idea. I didn't test it.
Try the following code: it creates an alarm for a specific time in a day using alarmanager and repeat it daily...
Declare
Calendar cal_alarm;
Now set the calender object for specific time to alarm
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm a");
String time=""21 12 2016 8:10 AM"
cal_alarm = Calendar.getInstance();
cal_alarm.setTime(dateFormat.parse(time));
Set the alarm
public void set_alarm() {
Calendar calNow = Calendar.getInstance();
long current_time = calNow.getTimeInMillis();
Log.d("ALARM CALENDER VALUES", cal_alarm.toString());
long alarm_time_in_millis = cal_alarm.getTimeInMillis();
//check if time is alreday passed or not
if (alarm_time_in_millis > current_time) {
new Alarm_task(getApplicationContext(), cal_alarm).run();
}
public class Alarm_task implements Runnable {
// The date selected for the alarm
private final Calendar cal;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
long alarm_time2;
int _id;
public Alarm_task(Context context, Calendar cal) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.cal = cal;
this._id = (int) System.currentTimeMillis();
alarm_time2 = cal.getTimeInMillis();
//Toast.makeText(getActivity(), alarm_time2 + " ", Toast.LENGTH_SHORT).show();
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent i = new Intent("com.package_name");
i.setAction("com.package_name");
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getApplicationContext(), _id, i, PendingIntent.FLAG_UPDATE_CURRENT);
/** Converting the date and time in to milliseconds elapsed since epoch */
long alarm_time = cal.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time each day*/
am.setRepeating(AlarmManager.RTC_WAKEUP, alarm_time, AlarmManager.INTERVAL_DAY, operation);
}
}
Now in manifest define an explicit activity which handle the alarm intent and show popup dialog and notification during alarm time
<activity
android:name=".Prereminder"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
//same as your alarm task
<action android:name="com.package_name" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Now in your Prereminder.java
public class Prereminder extends FragmentActivity {
String msg = "Helloo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
sendNotification();
/** Creating an Alert Dialog Window */
Reminder_alert alert = new Reminder_alert();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "Reminder_alert");
}
private void sendNotification() {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
//handle notification on click
Intent myintent = new Intent(this, Home_page.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_small)
.setContentTitle("Alarm")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Now your Reminder_alert class show the popup dialog during alarm:
public class Reminder_alert extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("ALARM ON");
/** Setting the content for the alert dialog */
builder.setMessage("WAKE UP NOW");
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
/** Creating the alert dialog window */
return builder.create();
}
/**
* The application should be exit, if the user presses the back button
*/
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
}
1- in simple way first use this function to create alarm
private void createAlarm(Date start_alarm_date, String schedual_type ,String schedule_id){
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, PushLocalNotification.AlarmReceiver.class);
intent.setAction("Your_Action_Name"); //this action you will use later
intent.putExtra("Extra", any_extra_you_want_add);// remove if you want add extra
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at specific date
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// repeat it "daily":
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
2- create IntentService and make your receiver extend BroadcastReceiver
public class PushLocalNotification extends IntentService {
private NotificationManager mNotificationManager;
private String mScheduleID;
NotificationCompat.Builder builder;
public PushLocalNotification() {
super("pushLocalNotification");
}
#Override
protected void onHandleIntent(Intent intent) {
// call create local notification here
}
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("Your_action_Name")) {
// call service here.
Intent sendIntent = new Intent(context, PushLocalNotification.class);
sendIntent.putExtra("Extra_name", intent.getStringExtra("Previos_extra_you_add_before"));
context.startService(sendIntent);
}
}
}
private void createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Create Intent to launch this Activity again if the notification is clicked.
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(intent);
// Sets the ticker text
builder.setTicker(getResources().getString(R.string.custom_notification));
// Sets the small icon for the ticker
builder.setSmallIcon(R.drawable.ic_stat_custom);
// Cancel the notification when clicked
builder.setAutoCancel(true);
// Build the notification
Notification notification = builder.build();
// Inflate the notification layout as RemoteViews
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
// Set text on a TextView in the RemoteViews programmatically.
final String time = DateFormat.getTimeInstance().format(new Date()).toString();
final String text = getResources().getString(R.string.collapsed, time);
contentView.setTextViewText(R.id.textView, text);
/* Workaround: Need to set the content view here directly on the notification.
* NotificationCompatBuilder contains a bug that prevents this from working on platform
* versions HoneyComb.
* See https://code.google.com/p/android/issues/detail?id=30495
*/
notification.contentView = contentView;
// Add a big content view to the notification if supported.
// Support for expanded notifications was added in API level 16.
// (The normal contentView is shown when the notification is collapsed, when expanded the
// big content view set here is displayed.)
if (Build.VERSION.SDK_INT >= 16) {
// Inflate and set the layout for the expanded notification view
RemoteViews expandedView =
new RemoteViews(getPackageName(), R.layout.notification_expanded);
notification.bigContentView = expandedView;
}
// START_INCLUDE(notify)
// Use the NotificationManager to show the notification
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, notification);
}
}
3- final step don't forget to declare service and receiver inside manifest file
<receiver
android:name=".PushLocalNotification$AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="Your_Action_name:)" />
</intent-filter>
</receiver>
<service android:name=".PushLocalNotification" />
be patient and have fun :)
Create a method which contains your Code where you will define your Time or at what time you want to show the notification.This method need to be called from where you want user to ask for notification.
public void getNotification () {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 00);
if (now.after(calendar)) {
Log.d("Hey","Added a day");
calendar.add(Calendar.DATE, 1);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Create a Notification_receiver class which is going to extend Broadcast Receiver here you are going to define your Channel Id as it is perfectly working for API 25 and above this the Notification_receiver class:
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
//Created By Prabhat Dwivedi
public class Notification_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Your App Name",
"You app Package Name",
NotificationManager.IMPORTANCE_HIGH);
String channel_Id = channel.getId();
CharSequence channel_name = channel.getName();
Log.e("Notification_receiver", "channel_Id :" + channel_Id);
Log.e("channel_name", "channel_name :" + channel_name);
channel.setDescription("Make entry of today's spending now");
notificationManager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.yourapp_logo)
.setChannelId("Your app Name is your Channel Id")
.setContentTitle("Your title")
.setContentText("Your Description")
.setAutoCancel(true);
//nder this you will find intent it is going to define after clicking notification which activity you want to redirect
Intent repeatingIntent = new Intent(context, HomePage.class);
pendingIntent = PendingIntent.getActivity(context, 100, repeatingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
notificationManager.notify(100, builder.build());
}
}
Kindly also add the Notification receiver inside AndroidManifest.xml file
<receiver android:name=".Notification_receiver"/>
I am trying to learn AlarmManager in android.I came across the doc to understand the use of AlarmManager.ELAPSED_REALTIME_WAKEUP .But when i used this in my app and when the app ran,i clicked the back button thinking that alarm manager will again call the activity after the alarm interval time set here
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+10*1000, alarmIntent);
But nothing happens.Please somenone explain the meaning of AlarmManager.ELAPSED_REALTIME_WAKEUP.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent = PendingIntent.getActivity(this, 0, intent,0);
Log.d("asd","initialized alarmintent");
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+10*1000, alarmIntent);
Log.d("asd", "alarm set");
}
}
AlarmReceiver.java
public class AlarmReceiver extends AppCompatActivity
{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent_layout);
Log.d("asd","writing textview");
tv=(TextView)findViewById(R.id.textview);
tv.setText("called");
}
}
I would use AlarmManager.RTC_WAKEUP as opposed to AlarmManager.ELAPSED_REALTIME_WAKEUP. Here is an example of how I was using AlarmManager in a recent app:
MainActivity.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
mAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// Cancel any existing service(s)
mAlarmManager.cancel(pendingIntent);
// Start service
long alarmTime = System.currentTimeMillis() + 10000L; // 10 seconds from now
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
}
AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() { }
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "AlarmService Triggered.", Toast.LENGTH_SHORT).show();
Log.d(this.getClass().getSimpleName(), "Service triggered");
}
}
it seems like your AlarmReceiver class was extending AppCompatActivity which won't work - you need to extend Broadcast Receiver as I have done. Then, within the onReceive() function in AlarmReceiver, you need to navigate to your desired Activity, like this:
Intent newIntent = new Intent(context, NewActivity.class);
context.startActivity(newIntent);
Try these changes and see if they work!
Your code should work fine.
Make sure you have declared your AlarmReceiver activity in the manifest, something like:
<activity
android:name=".AlarmReceiver"
android:label="#string/title_activity_alarm_receiver"
android:theme="#style/AppTheme.NoActionBar"></activity>
I can't stop my service with stopService(). I have tryed everything but it doesn't work. I stop my service only when I uninstall app.
public class Refresh extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "NESTO!", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Your location is: "+MyLocation(), Toast.LENGTH_LONG).show();
return START_NOT_STICKY;
}
#Override
public void onCreate() {
Intent myService = new Intent(this, Refresh.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,myService, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 20* 1000, pendingIntent);
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public LatLng MyLocation(){
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return new LatLng(location.getLatitude(), location.getLongitude());
}
}
And this is methods in main activity:
public void startService(){
startService(new Intent(getBaseContext(), Refresh.class));
}
public void stopService(){
stopService(new Intent(getBaseContext(),Refresh.class));
}
And this is how I call methods start and stop service:
public void onClick(View V){
stopService();
}
I think the alarm manager you are using to start the service is restarting the service for you,You have to stop that alarm,Stop the alarm like this
Intent intent = new Intent(this, YourService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pass the SAME ID FOR THE PENDING INTENT which you used while creating the pending intent
You kill the service, but the alarm is still set, you have to cancel the pending intent from the alarm manager in onDestroy
You have to cancel your AlarmManager, so service will not restart every 20sec.
After that you can use stopService() just please insert what service you want to stop.
Create a intent...
Intent intent = new Intent(getBaseContext(), Refresh .class);
When you want to start the service:
startService(intent);
When you want to stop the service:
stopService(intent);
and again, cancel your AlarmManager :) do it before you call stopService();
alarm.cancel(pendingIntent);
Alarm can restart the service. You should cancel it.