How to execute alarm on Android 10? - android

I want to ring alarm on exact time but below code is not working on Android 10.
If app is in stack alarm ring successfully but when its not in recent app stack it never run on any os version.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
manager.setAlarmClock(
new AlarmManager.AlarmClockInfo(
timeMillis,
PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0)
),
getIntent(context)
);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
manager.setExact(AlarmManager.RTC_WAKEUP, timeMillis, getIntent(context));
else
manager.set(AlarmManager.RTC_WAKEUP, timeMillis, getIntent(context));
Intent intent = new Intent("android.intent.action.ALARM_CHANGED");
intent.putExtra("alarmSet", true);
context.sendBroadcast(intent);
}
I have added below permission
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SET_ALARM" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.learntodroid.simplealarmclock.permission.ALARM" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
What can i do to ring alarm on Android 10?

To schedule an alarm at a specific time try this:
First Schedule an alarm at your desired time using Alarm Manager
void scheduleAlarm(Context context) {
// scheduling an alarm at 05:00 PM
//getting instance of a calendar
Calendar calendar = Calendar.getInstance();
//setting exact date and time of alarm
// in my case it is 17/11/2020 at 05.00 PM
calendar.set(Calendar.MONTH,10); // month count starts from 0; here 10 denotes November
calendar.set(Calendar.YEAR,2020); // year
calendar.set(Calendar.DAY_OF_MONTH,17); // day
calendar.set(Calendar.HOUR_OF_DAY,17); // hour
calendar.set(Calendar.MINUTE,0); // min
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,12345678,intent,PendingIntent.FLAG_CANCEL_CURRENT);
android.app.AlarmManager alarmManager = (android.app.AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5000,pendingIntent);
}
}
Then receive the alarm at the Broadcast Receiver
class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// this will trigger at the alarm time
// show notification or vibration here
}
}
Don't forget to add the receiver in your Manifest file:
<receiver
android:name=".AlarmReceiver" // need to specify the path of your receiver
android:enabled="true"
android:exported="true">
// this filter is optional, needed if you want to trigger the receiver even after a restart
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This should work for all android versions.

Android 10 won't start Activity from background task (alarm) if it won't have Intent.FLAG_ACTIVITY_NEW_TASK. try to replace new Intent(context, MainActivity.class) with intent object, which sould be declared as follows:
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
(optionally you may add also Intent.FLAG_ACTIVITY_CLEAR_TOP)

Related

Android alarm manager pending intents lost

This is my first post and I am new to Android App development so please bear with me.
I have written (and use every day) a pretty good reminders App because all the others were either too complicated or too simple. It is also on the play store, although not easy to find, but thats another story.
While I am happy with the whole App the alarms which show a notification or sound an alarm do not always happen. If the alarm is soon then it will but more than say 2 hours from now it often gets missed. Using "adb shell dumpsys alarm" it looks as if they are being discarded?
I have googled for days and have tried so many things, from this forum too, but no luck so I thought I would post some code to see if anybody can please tell me were I am going wrong as it should work as far as I can see.
So here goes.
I use alarm manager to queue the pending intent to call my broadcast receiver which starts a service which starts an activity which creates a notification and optionally sounds an alarm.
I was skipping the service bit but after googling it seems I should use a service. And as mentioned, this works fine for alarms happening soon but not after a few hours or a day or more. Could be due to Doze mode or my app being stopped by Android?
I would really appreciate some help please as I am pulling my hair out!!
Thanks in advance.
Here is my manifest. Where I think the problem is?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wingwares.reminders">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<supports-screens
android:anyDensity="true"
android:normalScreens="true" />
<application
android:icon="#drawable/reminder2"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<receiver android:name=".WidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<service
android:name=".WidgetService"
android:exported="false"
android:permission="android.permission.BIND_REMOTEVIEWS" />
<activity
android:name=".AppPreferences" />
<activity
android:name=".ListActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RemActivity"
android:label="#string/add_reminder"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan" />
<service
android:name=".AlarmService"
android:enabled="true"
android:exported="true" >
</service>
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="SET_ALERT" />
</intent-filter>
</receiver>
<activity
android:name=".AlarmDialog"
android:theme="#style/AlarmDialog" />
</application>
</manifest>
And my Alarm Manager from ListActivity
public void setAlert(Context context, boolean turnOn){
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("name", fullName());
intent.putExtra("notes", notes);
intent.putExtra("setalarm", setalarm);
intent.putExtra("millis", time.getMilliTime());
intent.putExtra("remId", remId);
pendingIntent = PendingIntent.getBroadcast(context, 8192 + remId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
if (turnOn) {
alertTime = time.getMilliTime() - (warning * 60000);
interval = getInterval();
//set repeating alarmManager just once
if (freq.equals(EVERY) && type.equals(FIXED) && date.equals(getOriginal()) && interval > 0) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, interval, pendingIntent);
} else {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
}
}
} else {
setalarm = false;
}
}
My broadcast receiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent newIntent = new Intent(context, AlarmService.class);
//pass the extras on and show the dialog
newIntent.putExtras(intent);
startWakefulService(context, newIntent);
}
}
My Service
public class AlarmService extends IntentService {
public AlarmService (){
super("AlarmService");
}
#Override
protected void onHandleIntent(Intent intent) {
Intent newIntent = new Intent(this, AlarmDialog.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//pass the extras on and show the dialog
newIntent.putExtras(intent);
startActivity(newIntent);
AlarmReceiver.completeWakefulIntent(newIntent);
}
}
My Activity (the notification part)
public class AlarmDialog extends Activity
implements DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
Bundle extras;
int remId;
String name, notes;
Boolean setalarm;
long alarmTime;
MediaPlayer player;
PendingIntent pendingIntent;
SharedPreferences mPrefs;
NotificationManager manager;
Notification notification;
static final int SNOOZE_BUTTON = -2;
static final int DISMISS_BUTTON = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create notification and alert box if alarmManager selected
mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
extras = getIntent().getExtras();
alarmTime = extras.getLong("millis");
remId = extras.getInt("remId");
name = extras.getString("name");
notes = extras.getString("notes");
setalarm = extras.getBoolean("setalarm");
//notification first
notification = new RemNotification(this, name).get();
if (notification != null) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(remId);
manager.notify(remId, notification);
}
}

Android——How can i know whether the app is autostart or not

I want to know whether the user allows autostart permissions of the app. I have already tried this:
ComponentName mComponentName = new ComponentName(getPackageName(),".AutoStartReceiver");
int a = getPackageManager().getComponentEnabledSetting(mComponentName);
the autostart permission can be granted and denied by security app,but I don't know how to get the status in my application.
such as the picture
you are probably using this permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
After that, you can implement a BroadcastReceiver:
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}}
And just add the class to your manifest-file:
<receiver android:enabled="true" android:name=".BootUpReceiver"
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>
To check directly, if you have Autostart permissions, use this:
int p = ContextCompat.checkSelfPermission(Activity.this, Manifest.permission.RECEIVE_BOOT_COMPLETED);
if (p == PackageManager.PERMISSION_GRANTED) {
//Yay, you have the receive boot completed (= Autostart) permission!
}
To get a list of receivers, registered for a specific intent, you can use
Use PackageManager and queryBroadcastReceivers().
To get a list for BOOT_COMPLETE, construct an intent with BOOT_COMPLETE action

Quickblox Push when App is Closed

I'm developing an app using Quickblox to create a chat with users. I've managed to get push services within the app, even when its in background but, once the app is force closed no push is received.
My android devices are registering on GMC QB services, the token appears and it registers with no problem.
Moreover I've even tried using the Push Admin on Quickblox but Push are not working either.
sourcecode:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<permission
android:name="com.myapp.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.myapp.app.permission.C2D_MESSAGE" />
<receiver
android:name="com.quickblox.chat.push.QBGcmBroadcastReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.myapp.app" />
</intent-filter>
</receiver>
<service android:name="com.quickblox.chat.push.QBGcmIntentServiceNewVersion"/>
<!-- CUSTOM -->
<service
android:name="com.myapp.app.push.CPInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name="com.myapp.app.push.CPRegistrationIntentService"
android:exported="false" />
And my BroadcastReceiver:
public class QBGcmBroadcastReceiver extends WakefulBroadcastReceiver {
public static int QBNotificationID = 4444;
#Override
public void onReceive(Context context, Intent intentReceived) {
Log.e(CPApplication.TAG, "QBGcmBroadcastReceiver -> Push RECIBIDA");
Log.e(CPApplication.TAG, "APP is ON ?() -> " + CPApplication.appIsON);
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), QBGcmIntentServiceNewVersion.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intentReceived.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
// App is not running
if (!CPApplication.appIsON) {
// Is New Message Push enabled ?
boolean isPushNewMessage = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_PUSH_NEW_MESSAGE, true);
// Is the user registered
boolean rememberPassword = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_REMEMBER_PASSWORD, false);
if (rememberPassword && isPushNewMessage) {
// Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(CPApplication.getInstance());
builder.setSmallIcon(R.drawable.push_icon)
.setTicker("Nuevo mensaje")
.setAutoCancel(true)
.setContentTitle(CPApplication.getInstance().getString(R.string.app_name))
.setContentText("Tiene un mensaje nuevo");
// Is New Message Sound enabled ?
boolean isSoundNewMessage = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_SOUND_NEW_MESSAGE, true);
if (isSoundNewMessage) {
builder.setDefaults(Notification.DEFAULT_SOUND);
}
// Intent
Intent intent = new Intent(CPApplication.getInstance(), SplashActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(CPApplication.getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Notification
Notification note = builder.build();
// Will show lights and make the notification disappear when the presses it
note.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager manager = (NotificationManager) CPApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(QBNotificationID, note);
}
}
}
}
I've also created an intent service class:
public class QBGcmIntentServiceNewVersion extends IntentService {
public static int QBNotificationID = 4444;
public QBGcmIntentServiceNewVersion() {
super(QBPushConstants.GCM_INTENT_SERVICE);
}
#Override
protected void onHandleIntent(Intent intentReceived) {
Log.i(CPApplication.TAG, "QBGcmIntentServiceNewVersion :: onHandleIntent");
// App is not running
// if (!CPApplication.appIsON) {
// Is New Message Push enabled ?
boolean isPushNewMessage = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_PUSH_NEW_MESSAGE, true);
// Is the user registered
boolean rememberPassword = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_REMEMBER_PASSWORD, false);
if (rememberPassword && isPushNewMessage) {
// Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(CPApplication.getInstance());
builder.setSmallIcon(R.drawable.push_icon)
.setTicker("Nuevo mensaje")
.setAutoCancel(true)
.setContentTitle(CPApplication.getInstance().getString(R.string.app_name))
.setContentText("Tiene un mensaje nuevo");
// Is New Message Sound enabled ?
boolean isSoundNewMessage = CPApplication.getSharedPrefs().getBoolean(CPConstants.SP_SOUND_NEW_MESSAGE, true);
if (isSoundNewMessage) {
builder.setDefaults(Notification.DEFAULT_SOUND);
}
// Intent
Intent intent = new Intent(CPApplication.getInstance(), SplashActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(CPApplication.getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Notification
Notification note = builder.build();
// Will show lights and make the notification disappear when the presses it
note.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager manager = (NotificationManager) CPApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(QBNotificationID, note);
}
// }
}
}
Thank you
Sorry, but I was putting the token instead of the deviceID, so it appears as a new registered device on QB admin, but with the wrong info, and that was the problem. I was using the new method from QB
new SendPushTokenToQBTask(token, deviceId).execute();
instead of
new SendPushTokenToQBTask(deviceId, token).execute()
Thank you anyways
Posting your permissions might also help but you didn't change the name in the receiver to your package name:
android:name="com.quickblox.chat.push.QBGcmBroadcastReceiver"
try changing it to:
android:name="com.myapp.app.QBGcmBroadcastReceiver"
if it doesn't work edit your question an add your permissions. Hope it helps.

Broadcast receiver is not getting invoked

I have used a Broadcast Receiver which is to be invoked when it finds internet Connection on the android device, to check if the Broadcast Receiver is running or not I have tried printing it in the logcat. I have no message being displayed.
I am invoking a service in my broadcast receiver which is also not getting invoked.
I have seen similar questions on stack overflow but still I am unable to solve the issue.
I am stuck with this since many days. Can anybody help me solve this problem?
This is my Broadcast receiver:
public final class ConnectivityReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("BRRRRRRRRRR","works!!!! In Broadcast Receiver...!!!");
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final PendingIntent wakeupIntent = PendingIntent.getService(context, 0,
new Intent(context, LocationUpdate.class), PendingIntent.FLAG_UPDATE_CURRENT);
final boolean hasNetwork = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (hasNetwork)
{
// start service now for doing once
context.startService(new Intent(context, LocationUpdate.class));
// schedule service for every 15 minutes
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, wakeupIntent);
}
else
{
alarmManager.cancel(wakeupIntent);
}
}
}
Manifest.xml
<receiver android:name="info.androidhive.loginandregistration.ConnectivityReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Since you are checking connectivity changes, i suggest you can first check if your app has permissions to connect to the internet.
The permission for the app to access the internet would be -
<uses-permission android:name="android.permission.INTERNET" />
Your receiver looks fine. Please, check if your package name is correct. Registering receiver in AndroidManifest.xml should me sufficient, but if it doesn't work for some reason, you can try different solution.
Try to register your receiver programmatically in the following way e.g. in onResume() method in your activity:
#Override
protected void onResume() {
super.onResume();
ConnectivityReceiver receiver = new ConnectivityReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(receiver, filter);
}
You should also unregister your receiver in onPause() method in the activity:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
If it won't help, you can add new permissions to AndroidManifest.xml file inside the tag.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

alarm does not show up

im trying to set a testalarm when i click on a button inside one of my fragments. but the alarm dosent show up.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "OnReceive alarm test", Toast.LENGTH_SHORT).show();
}
}
//Button is inside a Fragment
Button SetAlarmButton = (Button)(v.findViewById(R.id.SetAlarmButton));
SetAlarmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try{
Calendar alarm = Calendar.getInstance();
alarm.set(Calendar.HOUR_OF_DAY, 18);
alarm.set(Calendar.MINUTE, 00);
long alarmMillis = alarm.getTimeInMillis();
Intent intent = new Intent(view.getContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(view.getContext(), 192837, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) view.getContext().getSystemService(view.getContext().ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmMillis , pendingIntent);
}catch(Throwable e){AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
sw.toString();
builder.setMessage(sw.toString());
AlertDialog alert = builder.create();
alert.show();
}
}});
i know that i need to modify my manifest and add something like this but i dont know how and where exactly
<receiver android:name="AlarmReceiver">
....
</receiver>
to my manifest
<?xml version="1.0" encoding="UTF-8"?>
<manifest android:versionCode="1" android:versionName="1.0"
package="com.test.alarm" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application android:icon="#drawable/ic_launcher"
android:label="#string/app_name" android:theme="#style/AppTheme">
<activity android:label="#string/title_activity_main" android:name=".Main">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".First_Start"
/>
<activity
android:name=".Preferences"
android:label="Settings">
</activity>
</application>
</manifest>
Check out the docs for AlarmManager: http://developer.android.com/reference/android/app/AlarmManager.html
The Alarm that you're setting isn't related to the Alarm Clock functionality built in to the Clock application.
Alarms are used by the system to allow the application to respond to some event in the future. You basically tell the system you want your app to be woken up in some amount of time, and you define what Activity gets called when the Alarm goes off.
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_MESSAGE, "New Alarm");
i.putExtra(AlarmClock.EXTRA_HOUR, hours);
i.putExtra(AlarmClock.EXTRA_MINUTES, mins);
startActivity(i);
but with this i cant specify the day i want the alarm to be set

Categories

Resources