In the Android documentation for running a Service in the forground, the following example code is provided:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
However, this code does not work. Firstly, the constructor used for Notification is deprecated. Second, the method setLatestEventInfo(Context, String, String, PendingIntent) is no longer included in the Notification class. When I eliminate these and create a notification the correct way, an error occurs which looks like this:
Caused by: java.lang.NullPointerException: class name is null
at android.content.ComponentName.<init>(ComponentName.java:114)
at android.app.Service.startForeground(Service.java:654)
at com.vcapra1.motionsensors.MainActivity.startService(MainActivity.java:53)
EDIT: Here is the code I am using, from the link provided by @ RusheelJain:
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(ctx, MotionMonitorService.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, (int) System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification notification = new Notification.Builder(ctx)
.setContentTitle("Monitoring Motion")
.setContentText("No events yet...")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
// notificationManager.notify(1, notification);
startForeground(1, notification);
When I use the notificationManager.notify(1, notification);
line, a notification is created, but it is not persistent and does not start the Service (which, of course, is not meant to happen). However, when I use the startForeground(1, notification);
line, the app crashes with the above stack trace.
So my final question is: what is the correct way to start a Service that will keep running even if the app is closed? I have checked several sources and they all include the method which I found on the Android docs.