Make alarm Clock with BroadcastReceiver - android

I want to make a alarm clock in android and I write this with BroadcastReceiver But I have some problem with that...
I want to start alarm in specified time for example I want start alarm in every 3:50...
but when I am running the App alarming starting too...
There is my code bellow:
Any one could help me:
there is my broadcast Receiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
public static MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.tester.alarmmanager")) {
Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
mediaPlayer = MediaPlayer.create(context, R.raw.entezar);
mediaPlayer.start();
}
}
}
And in MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAlarm(03,50);
}
public void StartAlarm(int hour, int min){
Intent intent = new Intent(this, MyBroadcastReceiver.class);
intent.setAction("com.tester.alarmmanager");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),23433,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
Log.v("time picker",calendar.getTime()+"");
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,min);
calendar.set(Calendar.SECOND,00);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT){
alarmManager.setExact(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
Toast.makeText(MainActivity.this, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
Toast.makeText(MainActivity.this, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
}
}
And in Manifest:
<receiver android:name=".Utility.MyBroadcastReceiver">
<intent-filter>
<action android:name="com.tester.alarmmanager"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>

add after calendar.getInstance()
calendar.setTimeInMillis(System.currentTimeMillis())
or check code under this link https://github.com/mrkostua/SmartAlarm/blob/master/app/src/main/java/com/mrkostua/mathalarm/alarms/mathAlarm/AlarmManagerHelper.kt

Related

Service not starting in Android from AlarmManager after app is closed

Can anyone please correct my approach or suggest me the right ways for doing it.I have tried using broadcast receivers in place of services but that approach is not working for it.i.e I used getBroadcast() in place of getService() but didnt work.
It is working when the app is not closed from the application window but as soon as it is closed , the phone doesnt show notifications and ring as it was working in the case when the app wasn't closed.
MainActivity.class
`public class MainActivity extends AppCompatActivity {
TimePicker timePicker;
Button button;
AlarmManager alarmManager;
PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getHour(),
timePicker.getMinute(),
0
);
} else {
calendar.set(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute(),
0
);
}
Intent intent = new Intent(MainActivity.this,MyIntentService.class);
//This is the intent which will be fired
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
Log.e("TAG:","AlarmSet.");
// Log is showing the right statement i.e the alarm was set but it wasnt triggered when the app was closed from the application window
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onPause() {
super.onPause();
Log.e("TAG","OnPause.");
}
#Override
protected void onStop() {
super.onStop();
Log.e("TAG","OnStop.");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e("TAG","OnDestroy.");
}
}`
IntentService.class
`public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.e("TAG", "Starting service for notification and song");
Random random = new Random();
final Notification notification = new NotificationCompat.Builder(getApplicationContext(), "notify")
.setContentTitle("New Notification")
.setContentText("TIme for task.")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(Notification.PRIORITY_MAX)
.build();
final NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(random.nextInt(), notification);
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}`
Manifest file
`
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyIntentService"
android:enabled="true"
android:exported="true" />
</application>
</manifest>`

How to start service after reboot device in Android

I want start my Service after reboot device, I write below codes but when reboot device not start Service.
Manifest:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".alarm1.alarm1"></activity>
<receiver android:name=".alarm1.AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<!-- Will not be called unless the application explicitly enables it -->
<receiver android:name=".alarm1.DeviceBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Activity code:
public class alarm1 extends AppCompatActivity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm1);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAt10();
}
});
}
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 8000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancel() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 1000 * 60 * 20;
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 15);
Toast.makeText(alarm1.this, "Start at 17:11", Toast.LENGTH_SHORT).show();
/* Repeating on every 20 minutes interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 3, pendingIntent);
}
}
AlarmReceiver codes:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
DeviceBootReceiver codes:
public class DeviceBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
/* Setting the alarm here */
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int interval = 8000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(context, "Alarm Set", Toast.LENGTH_SHORT).show();
}
}
}
How can I fix this and when reboot device start Service?
Add permissions in Manifest.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Add receiver entry in Manifest.
<receiver android:enabled="true" android:name=".alarm1.DeviceBootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
You just need to
Request a permission
and
Explicitly enable the receiver.
The permission goes in the manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Then when the user sets an alarm (for example your start method), enable the boot receiver:
ComponentName receiver = new ComponentName(context, DeviceBootReceiver.class);
getPackageManager().setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
When the user cancels all alarms, you should disable the boot receiver using a similar piece of code.

how to change ringer mode in background(Vibrate or Silent)

I'm trying to write a program in which user can set time that will change ringer mode to vibrate or normal in background. When I set the start time it's working but at the end time it's not changing and device continuing vibrate mode.
I just want, at the start time phone would be in vibrate and at end time phone would go back into the silent mode.
MainActivity.java
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
Calendar calendar1 = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 4);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.AM_PM,Calendar.AM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, (int)System.currentTimeMillis(), myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
calendar1.set(Calendar.HOUR_OF_DAY, 4);
calendar1.set(Calendar.MINUTE, 38);
calendar1.set(Calendar.AM_PM,Calendar.AM);
Intent myIntent1 = new Intent(MainActivity.this, MyReceiver1.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, (int)System.currentTimeMillis(), myIntent1,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent);
}}
and these are related BroadcastReceiver class..
MyReceiver.java
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
AudioManager audio = (AudioManager)arg0.getSystemService(Context.AUDIO_SERVICE);
switch(audio.getRingerMode()){
case AudioManager.RINGER_MODE_NORMAL :
audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.d("MODE", "was normal");
Log.d("MODE", "is vibrate");
break;
case AudioManager.RINGER_MODE_SILENT :
audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.d("MODE", "was silent");
Log.d("MODE", "is vibrate");
break;
}
}}
MyReceiver1.java
public class MyReceiver1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AudioManager audio=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
// TODO Auto-generated method stub
switch(audio.getRingerMode()){
case AudioManager.RINGER_MODE_NORMAL :
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Log.d("MODE", "was normal");
Log.d("MODE", "is silent");
break;
}
case AudioManager.RINGER_MODE_VIBRATE :
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Log.d("MODE", "was vibrate");
Log.d("MODE", "is silent");
break;
}
}}
and I declared
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.media.RINGER_MODE_CHANGED" />
</intent-filter>
</receiver>
<receiver android:name=".MyReceiver1">
<intent-filter>
<action android:name="android.media.RINGER_MODE_CHANGED" />
</intent-filter>
</receiver>
in my manifest file.
Please help me to solve this issue.
Thanks.
Dont't use both the receiver (MyReceiver and Myreceiver1) use single MyReceiver.
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.media.RINGER_MODE_CHANGED" />
</intent-filter>
</receiver>

Alarm Manager with Broadcast Receiver (Toast in Receiver is not showing)

What am I doing wrong here? I have setalarm and wakelock in manifest. Im a beginner with Alarm Manager
public class AlarmManagerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
}
public void scheduleAlarm(View V)
{
Intent intentAlarm = new Intent(this, AlarmReceiverActivity.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
public class AlarmReceiverActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("YO!");
Toast.makeText(context, "Alarm Triggered in ", Toast.LENGTH_LONG).show();
}
}
Please help me, My goal is to update my database with alarm manager every 6 in the morning. It's like reseting a value so I limit the users activity for 1 day
I'll bet you forgot to register the BroadcastReceiver. You need, either, to:
registerReceiver(new AlarmReceiverActivity(), filter);
or, probably better in your case, in the Manifest
<receiver android:name="your.package.AlarmReceiverActivity">
<filter...
</receiver>

receiver and service

With the courtesy of an stackoverlow user we written this code. Should be starts a toast at specify hour but doesn't run.
Can someone help me to discover where's the problem?
thanks!
public class UnUsedService extends Service {
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//startService(new Intent(this, UnUsedService.class));
}
#Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// super.onStart();
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 22);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager) getApplicationContext().getSystemService (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}};
The receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
Manifest:
<service android:name="UnUsedService">
<intent-filter>
<action
android:name="org.gortcloud.startatboot.UnUsedService" />
</intent-filter>
</service>
<receiver android:name=".AlarmReceiver" android:process=":remote"/>
I was just working on something similar. can you replace receiver android:name=".AlarmReceiver" with receiver android:name=".AlarmReceiver" android:process=":remote" that worked for me.
ok...i got this to work. i followed How to start Service using Alarm Manager in Android?. basically i was using a pendingIntent.setBroadcast(..) which requires a BroadcastReceiver, now i'm using pendingIntent.setService(...)
i have a class that extends IntentService (with a noarg constructor). I'm successfully getting the alarm to trigger starting this service. i have an onStart() and onStartCommand() and onHandleIntent() that each get run (i assume you would only implement one of them)
hope this helps you.

Categories

Resources