Went through the documentation on how to start a service automatically after the device boots and tried all they said but couldn't get my service to work after rebooting the device, though it works perfectly well on first instance.
Below is my main activity (MainActivity.java) which starts the service after a button has been clicked, and triggers the service every 10 seconds using AlarmManager.
public void onClickSubmitDate(View view) {
Intent service = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, service, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 10 * 1000, pendingIntent);
//Enable receiver when device boots
ComponentName receiver = new ComponentName(this, BootReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
Below is my receiver class (BootReceiver.java)
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
10 * 1000, 10 * 1000,
pendingIntent);
}
}
}
My service contains a thread which checks for multiple scenarios and builds a notification for each scenario. Here's a sample below:
public int onStartCommand(Intent intent, int flags, int startId) {
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
Runnable r = new Runnable() {
#Override
public void run() {
try {
boolean diff = true;
if (diff) {
// Build the notification
notification.setSmallIcon(R.drawable.icon);
notification.setTicker(getString(R.string.notification_ticker));
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle(getString(R.string.notification_title));
notification.setContentText(getString(R.string.notification_1_text));
notification.setSound(alarmSound);
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
// Builds a notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Random r = new Random();
int rand = r.nextInt(1000);
nm.notify(rand, notification.build());
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Thread stephThread = new Thread(r);
stephThread.start();
return START_STICKY;
}
And finally below is my AndroidManifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.motherslove.stephnoutsa.myapplication18calendartest"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyDate"
android:label="#string/title_activity_my_date"
android:theme="#style/AppTheme.NoActionBar" />
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".BootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
Please can someone tell me what I've done wrong?
Thanks to help from #MikeM I could fix the problem.
Instead of
PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);
I had to pass in the context as the first argument, in the receiver, as shown below
PendingIntent pendingIntent = PendingIntent.getService(context, 0, service, 0);
Related
It's supposed to be a simple to do list app. You can set a list Item with a task and time. It should send you a notification at the given time.
Everything works fine when the app is running but when I close it I don't get notifications. I tried on API 23 and API R. I was looking at other posts but I couldn't find any solution.
Receiver class:
public class AlertReceiver extends BroadcastReceiver {
NotificationManagerCompat notificationManager;
#Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
boolean is24HourFormat = android.text.format.DateFormat.is24HourFormat(context);
CharSequence setTime;
if (is24HourFormat) {
setTime = DateFormat.format("HH:mm", calendar);
} else {
setTime = DateFormat.format("hh:mm a", calendar);
}
String currentTime = setTime.toString();
DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
Item itemForNotificationText = dataBaseHelper.GetNotificationContent(currentTime);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(itemForNotificationText.getTask())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentText(itemForNotificationText.getTime())
.build();
notificationManager.notify(dataBaseHelper.GetID(),notification);
}
}
I tired using setExactAndAllowWhileIdle but still doesn't work.
Start alarm:
public void startAlarm (Calendar c){
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, item.getNotification_id(), intent,0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}
}
Manifest file:
<application
android:name=".App"
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=".InsertActivity"></activity>
<activity
android:name=".ToDoList"
android:parentActivityName=".MainActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlertReceiver"/>
</application>
APP Class(Notification channel is created here):
public class App extends Application {
public static final String CHANNEL_1_ID = "Channel 1";
#Override
public void onCreate() {
super.onCreate();
CreateNotificationChannels();
}
private void CreateNotificationChannels () {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("Notifies you when an event has started.");
channel1.enableVibration(true);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
I try to start a ForegroundService by an BroadcastReceiver on Boot. I have tried this on a device with Android 8 and on an emulated Android 10 device. Both work fine. The problem is, that this code does not work on my Android 10 Galaxy S9. I have debugged everything, my BroadcastReceiver and the OnStartCommand method but also if the BroadcastReceiver runs the code fine, the OnStartCommand method does not start running.
I have a mainActivity in which the user has to apply this Process so the app gets opened once before the BroadcastReceiver should work.
I tried almost every solution i found here but nothing worked for me.
I don't understand why this is working on some devices but not on each. I hope someone can help me!
My min API is 26.
BroadcastReceiver
public class Restarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intentt = new Intent (context, MyService.class);
intentt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startForegroundService(intentt);
} else {
Intent intentt = new Intent (context, MyService.class);
intentt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(intentt);
}
}
}
Service
public class MyService extends Service {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
Log.d("WhereAreWe", "create");
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d("WhereAreWe", "StartCommand");
SharedPreferences check = getSharedPreferences("Checked", Context.MODE_PRIVATE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O){
Intent intents = new Intent(this, MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intents, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "newid")
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Foreground Service")
.setContentText("Example text")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
startForeground(1, builder.build());
}else{
startForeground(1, new Notification());
}
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.MyApplication">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
.
.
.
<receiver
android:name=".Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false" />
</application>
</manifest>
I'm trying to learn how to develop applications for Android devices. For some time I have been developing an application in which there is a function for sending notifications (reminders) at different times of the day. But if the phone is locked and the time to send the notification is more than 10 minutes then they do not come. Tried BroadcasrReceiver:
public class NotificationReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
addNotif(context, "Times UP Receiver", "5 second Receiver", "Alert Receiver");
}
private void addNotif(Context context, String msg, String msgText, String msgAlert) {
Notification.Builder builder = new Notification.Builder(context);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setPriority(Notification.PRIORITY_HIGH).setContentIntent(notifIntent)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_android_black_24dp))
.setTicker(msgAlert)
.setWhen(System.currentTimeMillis())
.setContentTitle(msg)
.setContentText(msgText);
Notification notification = builder.build();
notification.defaults = Notification.DEFAULT_ALL;
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(101, notification);
}
}
use AlarmManager:
Calendar calNotif = Calendar.getInstance();
Intent alertIntent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 102, alertIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager notifAlarm = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
notifAlarm.set(AlarmManager.RTC_WAKEUP, calNotif.getTimeInMillis() + (15 * 60 * 1000), pendingIntent);
I also tried to use Service:
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Calendar calNotif = Calendar.getInstance();
Intent alertIntent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 103, alertIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager notifAlarm = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
notifAlarm.set(AlarmManager.RTC_WAKEUP, calNotif.getTimeInMillis() + (16 * 60 * 1000), pendingIntent);
return START_STICKY;
}
}
Manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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>
<receiver android:name=".NotificationReceiver" />
<service android:name=".NotificationService" />
But nothing works. My head hurts, I still can not understand why notifications do not come. Tell me please what's the problem.
Don't use BaseContext and your going to test notification then why should you delayed 15 mins for notification. Minimize your time and check after its works increase your time.
In YourActivity
Calendar calNotif = Calendar.getInstance();
Intent alertIntent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 102, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager notifAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN)
notifAlarm.setExact(AlarmManager.RTC_WAKEUP, calNotif.getTimeInMillis()+10000, pendingIntent);
else
notifAlarm.set(AlarmManager.RTC_WAKEUP, calNotif.getTimeInMillis()+10000, pendingIntent);
In your Notification Code
builder.setPriority(Notification.PRIORITY_HIGH).setContentIntent(notifIntent)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_android_black_24dp))
.setTicker(msgAlert)
.setWhen(System.currentTimeMillis())
.setContentTitle(msg)
.setContentText(msgText);
Remove setLargeIcon beacause it uses Bitmap and takes more memory. After its worked you can implement using service.
This is my first time trying to make an app that starts on boot and runs in the background, and I'm finding all the possible ways of doing it a little confusing. I need the app to do a quick check of a few things every half hour, and sleep in between, so I settled for using AlarmManager and setRepeating.
In this test I've set it up so a boot receiver sets the alarm, which should run a service every 60 seconds (actual app will be 30+ mins between running this). The service triggers a notification, but when I reboot the phone, the notification only shows up once. I clear it and never see it again.
I'll post the relevant code below. Can anyone tell me where I'm going wrong? Thanks!
AlarmStarter.java
public class AlarmStarter extends BroadcastReceiver {
private static final int PERIOD = 60000;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
scheduleAlarms(context);
}
}
static void scheduleAlarms(Context ctxt) {
AlarmManager mgr = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, BackService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + PERIOD, PERIOD, pi);
}
BackService.java
public class BackService extends Service {
public BackService() {
//showNotification("ticker test", "title test", "content test", "http://google.com");
Log.d("CF", "Starting BackService");
showNotification("ticker test", "title test", "content test", "http://google.com");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
// Code to execute when the service is first created
}
public void showNotification(String ticker, String title, String content, String url) {
Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this).setTicker(ticker)
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testapp.test" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver
android:name=".AlarmStarter"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<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>
<service
android:name=".BackService"
android:enabled="true"
android:exported="true" ></service>
</application>
</manifest>
The problem I had here was that the BackService class I was trying to trigger with the alarm, was extending from the Service class. It should have extended from the BroadcastReceiver class, as only BroadcastReceivers can be triggered by the externally sent alarms.
I'm developing an android app, and part of it involves a notification that reminds the user to do something. This notification at a specified time and repeats every 12 hours. I'm using AlarmManager to schedule the alarm and I've also included the code to start my Alarm Service when the device boots. Here are my java classes:
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int i = preferences.getInt("numberoflaunches", 1);
if (i < 2) {
alarmMethod();
i++;
editor.putInt("numberoflaunches", i);
editor.commit();
}
}
private void alarmMethod() {
Intent intent = new Intent(this, AlarmService.class);
this.startService(intent);
Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
}
AlarmService.java
public class AlarmService extends Service {
//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarm manager instance
AlarmManager alarmMgr;
//Callback function for alarm manager event
BroadcastReceiver mReceiver;
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//Register AlarmManager Broadcast receive.
RegisterAlarmBroadcast();
}
#Override
public void onStart(Intent intent, int startid) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.HOUR_OF_DAY, 6);
alarmMgr.cancel(pendingIntent);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 60 * 12, pendingIntent);
}
private void showNotification() {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("app_name")
.setContentText("something")
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
.setSound(soundUri)
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build();
NotificationManagerCompat.from(this).notify(0, notification);
}
private void RegisterAlarmBroadcast() {
Log.i("RegisterAlarmBroadcast", "Register Intent.RegisterAlarmBroadcast");
//This is the call back function(BroadcastReceiver) which will be called when your alarm time is reached.
mReceiver = new BroadcastReceiver() {
private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
showNotification();
}
};
//Register the alarm broadcast here
registerReceiver(mReceiver, new IntentFilter("com.example.application.myNotification"));
pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.example.application.myNotification"), 0);
alarmMgr = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
}
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}
autostart.java
public class autostart extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1)
{
Intent intent = new Intent(arg0,AlarmService.class);
arg0.startService(intent);
Log.i("Autostart", "started");
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.application" >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".AlarmService"
android:enabled="true" />
</application>
However I must have done something wrong as it is not working properly. My problems are:
1. When I exit the app, the notification for some reason goes off, whatever the time is.
2. When I reboot, the notification goes off, whatever the time is.
I don't know if these problems are in any way related, maybe I have a piece of code that's messing everything up. But either way I would really appreciate any sort of help I can get. Thanks in advance.
The repeating interval should be 24 hours (1000 * 60 * 60 * 24), not 12 hours.
You are individually setting the time to 6 AM. So you can remove the line calendar.setTimeInMillis(System.currentTimeMillis());
EDIT:
I have made some of modifications to your code and finally got it working.
You problem was that you set an alarm for 6:00 AM. But you are setting this alarm at a time after 6:00 AM (say 9:00 AM). That is, you are setting an alarm for a past time. So it will go off immediately.
I made a work around for this. If the time you need to set alarm is past, set the alarm to trigger on the next day.
This is my modified code.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int i = preferences.getInt("numberoflaunches", 1);
if (i < 2) {
alarmMethod();
i++;
editor.putInt("numberoflaunches", i);
editor.commit();
}
}
private void alarmMethod() {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent("com.example.application.myNotification"),
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) (this
.getSystemService(Context.ALARM_SERVICE));
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.HOUR_OF_DAY, 6);
long mills = calendar.getTimeInMillis();
if (mills <= System.currentTimeMillis()) {
Calendar c1 = calendar;
c1.add(Calendar.DAY_OF_MONTH, 1);
mills = c1.getTimeInMillis();
} else {
mills = calendar.getTimeInMillis();
}
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, mills,
1000 * 60 * 60 * 24, pendingIntent);
Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT)
.show();
}
}
Autostart.java
public class Autostart extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1)
{
PendingIntent pendingIntent = PendingIntent.getBroadcast(arg0, 0, new Intent("com.example.application.myNotification"), 0);
AlarmManager alarmMgr = (AlarmManager) (arg0.getSystemService(Context.ALARM_SERVICE));
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.HOUR_OF_DAY, 6);
long mills = calendar.getTimeInMillis();
if (mills <= System.currentTimeMillis()) {
Calendar c1 = calendar;
c1.add(Calendar.DAY_OF_MONTH, 1);
mills = c1.getTimeInMillis();
} else {
mills = calendar.getTimeInMillis();
}
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, mills, 1000 * 60 * 60 * 24, pendingIntent);
Log.i("Autostart", "started");
}
}
Alarmer.java
public class Alarmer extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
private void showNotification(Context context) {
Random r = new Random();
int r0 = r.nextInt();
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("app_name")
.setContentText("something" + r0)
.setContentIntent(
PendingIntent.getActivity(context, 0, new Intent(context,
MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))
.setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true).setOnlyAlertOnce(true).build();
// NotificationManagerCompat.from(this).notify(0, notification);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(r0, notification);
}
}
AndroiManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/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=".autostart" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".Alarmer" android:enabled="true">
<intent-filter>
<action android:name="com.example.application.myNotification" />
</intent-filter>
</receiver>
<service
android:name=".AlarmService"
android:enabled="true" />
</application>
</manifest>
Compare it with your code and make changes.