I am setting an AlarmaManager event, but my BroadcastReceiver doesn't catch it:
String task_uuid = UUID_Generator.getUUID();
Intent task_intent = new Intent(getApplicationContext(),AlarmReciever.class);
task_intent.putExtra("task_id", task_uuid);
task_intent.putExtra("test", 10101010);
PendingIntent operation =
PendingIntent.getActivity(getBaseContext(),0, task_intent, 0);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
long alarm_time = dateTime.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
AlarmReceiver:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
System.out.println("test!!!");
try {
SMSUtills.sendSMS("0504235325", "נסיון תזמון");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Add this:
startActivity(task_intent);
I have used this code in my project it's work fine:
Intent myIntent1 = new Intent(PrayerTimeActivity.this, AlarmReceiverFri.class);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(PrayerTimeActivity.this,0, myIntent1, 0);
alarmManager1.set(AlarmManager.RTC_WAKEUP,Calendar_Object.getTimeInMillis(), pendingIntent1);
and the receiver class is:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiverFri extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// When our Alaram time is triggered , this method will be excuted (onReceive)
// We're invoking a service in this method which shows Notification to the User
Intent myIntent = new Intent(context, NotificationServiceFri.class);
context.startService(myIntent);
}
}
and in AndroidManifest.xml also contain
<receiver android:name=".AlarmReceiverFri" />
Thanks!!!
If my answer will help you then don't forget to accept this answer. :)
My problem is that I didn't specify wake lock permission in my manifast.
Related
I am developing an Android prayer app for Muslims. I have already developed the code to obtain the prayer times with the help of praytimes.org. Now I want to make it so that the user is notified at that time to pray. But for now, I just want to be able to send a notification at a certain time. Looking at the code and online resources, it seems to me as if it should work but for some reason, the notification is not displaying. I know the code for the notification part is correct because I created a button to create a notification using that code and it works. So I believe the problem is with the service, receiver, or alarmManager.
My guess is the problem has to do with the onStartCommand() method in MyNotificationService.java. I am not too familiar with services and their life-cycles so please go easy on me.
Thanks in advance.
In my MainActivity.java, here is the code in my onCreate() method.
/*========================Begin Notification Code==============================*/
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 18);
calendar.set(Calendar.HOUR_OF_DAY, 4);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent intent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
/*========================End Notification Code==============================*/
Here is MyReceiver.class
package com.ahmed.omar.tawheed;
/**
* Created by Omar on 1/18/15.
*/
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service = new Intent(context, MyNotificationService.class);
context.startService(service);
}
}
Here is MyNotificationService.java
package com.ahmed.omar.tawheed;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class MyNotificationService extends Service {
private NotificationManager notificationManager;
private int prayerNotificationID = 420; //blazeIt
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent1, int flag, int startId) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification n = new NotificationCompat.Builder(this)
.setContentTitle("Time to Pray")
.setContentText("It is now time to pray salah")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
n.flags = Notification.FLAG_AUTO_CANCEL;
// Sending the notification itself
notificationManager.notify(prayerNotificationID, n);
return START_STICKY;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Here are the lines from my AndroidManifest.xml
<service android:name=".MyNotificationService"
android:enabled="true" />
<receiver android:name=".MyReceiver"/>
See the documentation for Calendar.MONTH. The valid values start at 0 (for January), not 1. So, your code is trying to set an alarm on February 18, not January 18. Try changing the Calendar.MONTH value to 0 instead of 1.
This is what i do for send notification.
fun showNotification(context: Context,title: String, message: String) {
Log.e("notification", "visible")
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel("1",
"NAMAJ_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT)
channel.description = "namaj alarm channel"
mNotificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(context, "1")
.setSmallIcon(com.waltonbd.muslimcalender.R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(message)// message for notification
.setAutoCancel(true) // clear notification after click
val intent = Intent(context, MainActivity::class.java)
val pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
mBuilder.setContentIntent(pi)
mNotificationManager.notify(0, mBuilder.build())
}
I am learning how to build home screen widget in Android. This code is for an app widget to toggle RingerMode from NORMAL to SILENT and vice-versa.
This works fine but I need a full in-sight of logical flow (i.e which gets initiated when, goes where, does what, dies when) of all the intents in this.
Please help me understand this topic clearer.
package com.dummies.android.silentmodetoggle;
import android.app.Activity;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
public class AppWidget extends AppWidgetProvider {
public static String tag ="SilentModeToggleWidget";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(tag, "onReceive() first line");
if(intent.getAction()==null)
{
//Do Something
Log.d(tag, "before startService()");
context.startService(new Intent(context, ToggleService.class));
}
else{
super.onReceive(context, intent);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Do something in specified intervals
context.startService(new Intent(context, ToggleService.class));
}
public static class ToggleService extends IntentService{
public ToggleService(){
super("AppWidget$ToggleService");
Log.d(tag, "In ToggleService construcor");
}
#Override
protected void onHandleIntent(Intent arg0) {
Log.d(tag, "In ToggleService > onHandleIntent");
// TODO Auto-generated method stub
ComponentName cn = new ComponentName(this, AppWidget.class);
AppWidgetManager mgr = AppWidgetManager.getInstance(this);
mgr.updateAppWidget(cn, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
AudioManager audioManager = (AudioManager)context.getSystemService(Activity.AUDIO_SERVICE);
if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT){
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_on);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else{
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_silent);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
Intent i = new Intent(this, AppWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
return updateViews;
}
}
}
still not sure on what are u asking, but I'll try to answer, if not what u want, please explain in a different way.
Intent are usually started immediatly. You create an Intent can start it by calling startService or startActivity, so for example:
context.startService(new Intent(context, ToggleService.class));
on both times you wrote the above code, the service ToggleService is immediatly started.
PendingIntent on the other hand are saved to be started at later time, so for example
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
on the above line, the AppWidget Broadcast is started when the user clicks on R.id.phoneState in your HomeScreen AppWidget.
Each PendingIntent is stored in the system with a certain ID, this ID is the requestCode parameter (you used zero on your code)... that means, that if you create a different PendingIntent with the same ID it will override it, meaning a different action will be started when the user clicks on R.id.phoneState
I am new in android. I am working on an android alarm app.I want to show an alarm between 8am to 8pm after each 30 minutes and repeat this alarm daily.
My code is here.
Main Activity....
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class WaterActivity extends Activity {
Button leftBTN, rightBTN;
Switch toggleSwitch;
Context context = this;
SharedPref pref;
static PendingIntent pendingIntent;
static AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water);
leftBTN = (Button)findViewById(R.id.leftbtn);
rightBTN = (Button)findViewById(R.id.rightbtn);
toggleSwitch = (Switch)findViewById(R.id.switchbtn);
pref = new SharedPref(context);
if(pref.getValue(pref.getWaterKey()).equals("on"))
toggleSwitch.setChecked(true);
toggleSwitch.setOnCheckedChangeListener(SwitchListener);
leftBTN.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
leftBTN.setTextColor(getResources().getColor(R.color.water_color));
rightBTN.setTextColor(getResources().getColor(R.color.white_color));
leftBTN.setBackgroundResource(R.drawable.button_bg);
rightBTN.setBackgroundResource(R.drawable.button_right_bg2);
}
});
rightBTN.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
rightBTN.setTextColor(getResources().getColor(R.color.water_color));
leftBTN.setTextColor(getResources().getColor(R.color.white_color));
rightBTN.setBackgroundResource(R.drawable.button_right_bg);
leftBTN.setBackgroundResource(R.drawable.button_bg2);
}
});
}
private Switch.OnCheckedChangeListener SwitchListener = new Switch.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
pref.savePre_value(pref.getWaterKey(), "on");
Toast.makeText(context, "Reminder is on", Toast.LENGTH_SHORT).show();
Intent intentsOpen = new Intent(context, WaterReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context,111, intentsOpen, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10000, pendingIntent);
} else {
pref.savePre_value(pref.getWaterKey(), "off");
Toast.makeText(context, "Reminder is off", Toast.LENGTH_SHORT).show();
alarmManager.cancel(pendingIntent);
}
}
};
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
}
and this is my Receiver.
public class WaterReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.",
Toast.LENGTH_LONG).show();
}
}
Please help what am i missing here?
How can i do this in android.any one can help me in this?
Thanks in start.
Preety simple process:
Schedule a daily alarm exclusively to start at 8AM
Once your daily alarm is hit, schedule another one to repeat 30 min preodically
on each subsequent trigger of second alarm, check if time is passed 8PM, if yes then remove it.
It would be fairly simple to implement, sample code
public void setDailyAlarms(Context context){
// Daily Alarm
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
Intent intent = new Intent("DAIL_ALARM_TRIGGERED");
PendingIntent pIntent = PendingIntent.getBroadcast(context,
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent);
}
public void setRepeatingAlarm(Context context){
// Alarm 30 min each'
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("REPEATING_ALARM_TRIGGERED");
PendingIntent pIntent = PendingIntent.getBroadcast(context,
102, intent, PendingIntent.FLAG_UPDATE_CURRENT);
manager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 30*60*1000, pIntent);
}
public void cancelRepeatingAlarm(Context context){
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("REPEATING_ALARM_TRIGGERED");
PendingIntent pIntent = PendingIntent.getBroadcast(context,
102, intent, PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pIntent);
}
Now, you need a broadcast receiver to receive "DAIL_ALARM_TRIGGERED" intent, once you receive this you call setRepeatingAlarm(), now this will fire broadcast "REPEATING_ALARM_TRIGGERED" once you receive this just check if present time is 8PM is yes then call cancelRepeatingAlarm();
I guess this would be sufficent for you to implement your logic.
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.
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());