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);
}
}
}
Related
I want to have an app that do s.th in specific time even phone is on sleep mode. I used these code but receiver dosent work correctly. The Log just show some times. for example every two or three minute Log showed. what should I do that app work when time changed on phone.
I also tried wakeLock and alertManager class but nothing changed.
public class MyService extends Service {
private static final String CHANNEL_ID = "1";
private static final int NOTIFICATION_ID = 1;
private static final CharSequence CHANNEL_NAME = "channel name";
private TimeChange timeChange;
private CharSequence notificationContent = "hi";
private NotificationManager manager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotification();
startNotification();
timeChange = new TimeChange();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_TIME_TICK);
registerReceiver(timeChange, filter);
return START_STICKY;
}
public class TimeChange extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("4040", "hi");
}
}
private void startNotification() {
// run activity when notification clicked
Intent mainActivity = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,
mainActivity, PendingIntent.FLAG_UPDATE_CURRENT);
// show notification
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentText(notificationContent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
}
private void createNotification() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID , CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH);
manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(timeChange);
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serVice = new Intent(MainActivity.this, MyService.class);
ContextCompat.startForegroundService(this, serVice);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.android.prj.myapplication">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".MyService$TimeChange"
android:enabled="true"
android:exported="true"
tools:ignore="Instantiatable" />
</application>
</manifest>
I have a problem and that is that the service I use in an Android project does not work when I disconnect the device from the power. If it is connected, it does work. I have tried many alternatives and the last thing I tried is this.
I need help... anything that can solve this problem?
Android Manifest and Service
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.resolucion.probando" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<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/Theme.Probando" >
<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=".SegundaActivity"></activity>
<service android:process=":remote" android:name=".NuevoIntento"></service>
</application>
</manifest>
public class NuevoIntento extends Service {
private ScheduledExecutorService scheduleTaskExecutor;
private Context context;
TextView tv;
int hora;
int minutos;
int seconds;
int minutosumado;
#Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "Service binding");
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
setNotification();
if (scheduleTaskExecutor == null) {
scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new mainTask(), 0, 10, TimeUnit.SECONDS);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_main, null);
tv = layout.findViewById(R.id.hora);
return Service.START_STICKY;
}
public void setNotification() {
PendingIntent contentIntent;
contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MainActivity")
.setSmallIcon(R.drawable.ic_launcher_background)
.setColor(this.getResources().getColor(R.color.black))
.setOngoing(true)
.setAutoCancel(false)
.setContentText("MyApp");
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(101, mBuilder.build());
Notification notification = mBuilder.build();
startMyOwnForeground(); //NOTIFICATION_ID is a random integer value which has to be unique in an app
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
private class mainTask implements Runnable {
public void run() {
Log.e("TAG","TAG");
}
}
}
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);
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.
I created an app which is a Book Shelf, because I borrow books very often, I use BroadcastReceiver to send notifications when the screen is on. But, the BroadcastReceiver works only if the app is opened (the notification don't show when it's closed).
MyReceiver.java
public class MyReceiver extends BroadcastReceiver
{
public static final int ID_NOTFICATION_REMINDER = 0;
SharedPreferences sp = MainActivity.sp;
SharedPreferences.Editor edit = MainActivity.edit;
private NotificationManager mNotificationManager;
#SuppressWarnings("deprecation")
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().matches("android.intent.action.SCREEN_ON"))
{
for (int i = 0; i < sp.getInt("count", 0); i++)
{
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String name = sp.getString("name" + i, "NULL");
String owners = sp.getString("owner" + i, "NULL");
String holder = sp.getString("where" + i, "NULL");
String date = sp.getString("date" + i, "NULL");
SimpleDateFormat dfDate = new SimpleDateFormat(
"dd-MM-yyyy");
Calendar c = Calendar.getInstance();
String currentDate = dfDate.format(c.getTime());
if ((!owners.equals(holder)) && (!name.isEmpty()) && (Utils.monthDiff(date, currentDate) >= 30))
{
int icon = R.drawable.book_shelf_icon;
CharSequence tickerText = "A message from Book Shelf";
long when = System.currentTimeMillis();
final Notification mNotification = new Notification(icon, tickerText, when);
String contentTitle = "The book "+name+" hasn't changed it's state for over a month!";
String contentText = "Tap to open Book Shelf";
Intent mIntent = new Intent(context, MainActivity.class);
PendingIntent mPendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);
mNotification.setLatestEventInfo(context, contentTitle, contentText, mPendingIntent);
mNotificationManager.notify(ID_NOTFICATION_REMINDER, mNotification);
}
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asaf.applications.bookshelf"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#drawable/book_shelf_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.asaf.applications.bookshelf.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.asaf.applications.bookshelf.MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
</application>
</manifest>
You are getting a reference to the SharedPreferences from the MainActivity
SharedPreferences sp = MainActivity.sp;
However when the activity isn't running, you will be getting a NPE (of sp =null )
A Broadacast reciever already has access to the context so use that to accuire a reference to the SharedPreferences
#SuppressWarnings("deprecation")
public void onReceive(Context context, Intent intent)
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
/*
* Your code
*/
}