I want to set One time alarm for certain Date and time. And i also set this by using alarm manager. But My problem is when device switch off and switch on then alarm is not wake up.
My code ::
public void setAlarm(String initialTime, String diffTime) throws ParseException {
Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
cal.set(Calendar.DATE,date);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.YEAR,year);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ChatScreen.this, AlarmNotificationReceiver.class);
i.putExtra("CoId", coId);
i.putExtra("DeptId", deptNo);
i.putExtra("CoName", companyName);
i.putExtra("DpLogo", dpLogo);
i.putExtra("DeptName",deptName);
i.setAction("isFromAlram");
PendingIntent pi = PendingIntent.getBroadcast(ChatScreen.this,0, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pi);
}
My AlarmReceiverclass :::
public class AlarmNotificationReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("AlarmReceiver",action);
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(context, "ALARM_BOOT_COMPLETED", Toast.LENGTH_LONG).show();
} else if (action.equals("isFromAlram")) {
Logger.errorLog("From Service", "yes");
}
}
}
and also give permission in menifest file android:name="android.permission.RECEIVE_BOOT_COMPLETED"
receiver
android:name="com.chatapi.ChatApi.MyBroadcastReceiver"
android:enabled="true"
EDIT Here the complete manifest entry for the receiver
<receiver android:name=".AlarmNotificationReceiver"
android:enabled="true"
android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="isFromAlram" > </action>
</intent-filter>
</receiver>
You should add logging to see if your BroadcastReceiver is being called on device boot. Using Toast for this is a bad idea, you may never get to see it. Use logging and check your logcat.
Alarms are not preserved over device boots. When the device boots, your BroadcastReceiver should get called. You then need to set the alarm again.
Related
I'm attempting to make it so my app runs some code once per day at 6AM. This works just fine when the app is open and in the foreground, but if the app is closed by swiping it away, the code is never called at the appropriate time.
AlarmReceiver.java (For testing purposes, I have it just trying to display a Toast to verify it runs)
public class AlarmReceiver extends BroadcastReceiver {
public static final String intentAction = "com.mpagliaro98.action.NOTIFICATIONS";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(intentAction)) {
Toast.makeText(context, "RECEIVER CALLED", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java (Where the alarm is being set)
public class MainActivity extends AppCompatActivity {
...
private void setRecurringAlarm() {
// Set this to run at 6am
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
updateTime.set(Calendar.HOUR_OF_DAY, 6);
updateTime.set(Calendar.MINUTE, 0);
updateTime.set(Calendar.SECOND, 0);
updateTime.set(Calendar.MILLISECOND, 0);
// Build the pending intent and set the alarm
Intent i = new Intent(AlarmReceiver.intentAction);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(),
0, i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
assert am != null;
am.setRepeating(AlarmManager.RTC, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}
}
AndroidManifest.xml (Just the relevant parts)
<uses-permission android:name="android.permission.SET_ALARM" />
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.mpagliaro98.action.NOTIFICATIONS" />
</intent-filter>
</receiver>
I've read through dozens of similar problems to this on this site and elsewhere and I'm seriously at a loss for why this won't work. Any help would be appreciated.
Try changing receiver to
<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>
Should I use android: process =":remote" in my receiver?
I am try to set a alarm to restart app on 8:30.am in every day , so I design service and receiver,
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
</intent-filter>
</receiver>
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)){ //not working ?
Log.d("BootReceiver", "screen on completed");
Intent Alarm = new Intent(context,LongRunningService.class); //start Service
context.startService(Alarm);
}
if (Intent.ACTION_BOOT_COMPLETED.equals(action)){ //not working ?
Log.d("BootReceiver", "system boot completed");
Intent Alarm = new Intent(context,LongRunningService.class); //start Service
context.startService(Alarm);
}
if ("startAlarm".equals(intent.getAction())){
Intent home = new Intent(context, MainActivity.class);
home.putExtra("RELOAD",1);
home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(home);
}
LongRunningService.java
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable(){
#Override
public void run() {
Log.i(TAG, "run: executed at "+ new Date().toString()); //not working?
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 00);
}
In fact , I start service in MainActivity , but I don't want to start service
onCrate in MainActivity , because My alarm set 8:30 to restart MainActivity,
that will be problem , 8:30:00 ~ 8:30:30 will repeat restart my app....
According to docs
Apps that target Android 8.0 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest. An implicit broadcast is a broadcast that does not target that app specifically
So, if you want receive this broadcast you need to register them during app run (and it will work only if you app not destroyed).
JobScheduler will better fit your needs, i think.
I am trying to make an app that allows the user to enter two times using two TimePickers and the phone will set to silent between these times. I am using PendingIntent and AlarmManager to trigger the BroadcastReceiver at the times the user chooses.
At the moment, it is setting the phone on and off silent immediately when the user clicks the save button. My "alarm scheduled" toast then appears and my "broadcast received" appears twice but it doesn't do anything after that.
Here is my main activity code:
public class MainActivity extends AppCompatActivity {
AlarmManager alarm;
TimePicker timePickerStart;
TimePicker timePickerEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePickerStart = (TimePicker)findViewById(R.id.timePickerStart);
timePickerStart.setIs24HourView(true);
timePickerEnd = (TimePicker)findViewById(R.id.timePickerEnd);
timePickerEnd.setIs24HourView(true);
}
//method is called when save button is clicked
public void setAlarm(View view) {
Calendar calendarStart;
Calendar calendarEnd;
calendarStart = Calendar.getInstance();
calendarEnd = Calendar.getInstance();
//Set calendars to the times in both TimePickers
calendarStart.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, timePickerStart.getCurrentHour(), timePickerStart.getCurrentMinute());
long startTimeMillis = calendarStart.getTimeInMillis();
calendarEnd.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, timePickerEnd.getCurrentHour(), timePickerEnd.getCurrentMinute());
long endTimeMillis = calendarEnd.getTimeInMillis();
//create an intent and set the class that will be triggered by the intent
Intent intent = new Intent(MainActivity.this, Receiver.class);
PendingIntent pIntent = null;
pIntent = PendingIntent.getBroadcast(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//create alarm manager
alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set alarms to go off at the time specified by the timePickers
alarm.set(AlarmManager.RTC_WAKEUP, calendarStart.getTimeInMillis(), pIntent);
alarm.set(AlarmManager.RTC_WAKEUP, calendarEnd.getTimeInMillis(), pIntent);
//Toast for feedback
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_SHORT).show();
}
Here is my BroadcastReceiver:
public class Receiver extends BroadcastReceiver {
AudioManager audioManager;
int modeNum;
#Override
public void onReceive(Context context, Intent intent) {
//toast for feedback
Toast.makeText(context, "Broadcast Received", Toast.LENGTH_SHORT).show();
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
modeNum = audioManager.getRingerMode();
if (modeNum == 0) {
audioManager.setRingerMode(2);
} else {
audioManager.setRingerMode(0);
}
}
}
This is my Manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Receiver"></receiver>
</application>
You have multiple problems.
First, you are trying to create two alarms with the same PendingIntent. That will not work. Your second alarm request will cancel the first one. You need distinct PendingIntent objects, which means either substantially different Intent objects wrapped by the PendingIntent objects, or use two different values where you have 123.
Second, your set() calls on Calendar are incorrect. For example, in both places, your first parameter is supposed to be year. You are passing Calendar.YEAR, which is 1, not 2015.
here is my manifest
<receiver android:name=".MyCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and
public class MyCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
some code
}
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE) || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
some code
}
}
}
it is works but after sometime that press back button and phone be idle it doesn't work any more
(i added "android.os.Process.killProcess(android.os.Process.myPid());" at the end of my code and now it is better and work for maybe 2 3 hour after last execute)
You can use alarm manger to broadcast receiver after certain interval of time like this.
public static void scheduleTestAlarmReceiver(Context context) {
Intent receiverIntent = new Intent(context, TestAlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 123456789, receiverIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+startDelay, someDelay, sender);
}
I have 3 applications that are dependent on each other. for instance, Client app, Browser and launcher. My requirement is when the client is uninstalled(only when the client) i want the other two apps to be uninstalled as well. For this what i have done so far is, i have written a broadcast receiver(in both the apps) that listens for package removed. if the package removed is my client, i start an alarm that launches the uninstall procedure(individually on both apps). Why the alarm? because i want the uninstall pop up to come up til the user uninstalls the app. The issue i am currently facing is that, sometimes the launcher app does not get the broadcast or so i think. and hence it does not initiate the uninstall. Sometimes it does and sometimes it doesn't. I am not able to figure out the cause of this problem. below is the code written in the launcher:
The broadcast receiver :
public class UnistallBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
String packagename = intent.getData().getSchemeSpecificPart();
if (packagename.equalsIgnoreCase("com.android.nanoheal")) {
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
Intent intent1 = new Intent(context, AlarmIntent.class);
intent1.putExtra("appnamel", "com.nanoheal.launcher");
PendingIntent pi = PendingIntent.getBroadcast(context, 325,
intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 30, pi);
}
}
}
}
the Alarm Intent:
public class AlarmIntent extends BroadcastReceiver {
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
Log.d("AlarmIntent", "Intent fired by Launcher");
mContext = context;
try {
String appLauncher = intent.getStringExtra("appnamel");
if (appLauncher != null) {
if (isAppInstalled(appLauncher)) {
Uri packageURI2 = Uri.parse("package:" + appLauncher);
Intent uninstallIntent2 = new Intent(
Intent.ACTION_UNINSTALL_PACKAGE, packageURI2);
uninstallIntent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(uninstallIntent2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isAppInstalled(String packageName) {
PackageManager pm = mContext.getPackageManager();
boolean installed = false;
try {
pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
Log.d("AlarmIntent", "Launcher-IsAppInstalled " + packageName + " "
+ installed);
return installed;
}
}
I am not very certain about the details of how and why.
But i changed this
<receiver android:name="package.UnistallBroadcast" >
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
to
<receiver android:name="package.UnistallBroadcast" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
and it worked fine. As far as i know if the priority is set for a receiver the one with the highest priority should get the action first. but strangely, in my case i was not getting the action for the receiver i gave priority.