Always show service in notification bar - android

I want to add my app to the notification bar so that it always shows, like some apps in the Google Play store.
I want it to be like this screen shot:
I want my notification to not be cleared, and for my app to be opened when the notification is clicked.
Here's My Service Class Code:
package com.demo;
import java.util.Random;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;
public class ServiceExample extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service Created",300).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"Service Destroy",300).show();
}
#Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(this,"Service LowMemory",300).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this,"Service start",300).show();
Notification notification = new Notification(R.drawable.ic_launcher,
"Rolling text on statusbar", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,
"Notification title", "Notification description", contentIntent);
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"task perform in service",300).show();
/*ThreadDemo td=new ThreadDemo();
td.start();*/
Notification notification = new Notification(R.drawable.ic_launcher,
"Rolling text on statusbar", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,
"Notification title", "Notification description", contentIntent);
startForeground(1, notification);
return super.onStartCommand(intent, flags, startId);
}
private class ThreadDemo extends Thread{
#Override
public void run() {
super.run();
try{
sleep(70*1000);
handler.sendEmptyMessage(0);
}catch(Exception e){
e.getMessage();
}
}
}
private Handler handler=new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
showAppNotification();
}
};
void showAppNotification() {
try{
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// The PendingIntent to launch our activity if the user selects this
// notification. Note the use of FLAG_CANCEL_CURRENT so that, if there
// is already an active matching pending intent, cancel it and replace
// it with the new array of Intents.
// PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
// "My service completed", PendingIntent.FLAG_CANCEL_CURRENT);
// The ticker text, this uses a formatted string so our message could be localized
String tickerText ="djdjsdjkd";
// construct the Notification object.
Notification notif = new Notification(R.drawable.ic_launcher, tickerText,
System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
// notif.setLatestEventInfo(this, from, message, contentIntent);
// We'll have this notification do the default sound, vibration, and led.
// Note that if you want any of these behaviors, you should always have
// a preference for the user to turn them off.
notif.defaults = Notification.DEFAULT_ALL;
// Note that we use R.layout.incoming_message_panel as the ID for
// the notification. It could be any integer you want, but we use
// the convention of using a resource id for a string related to
// the notification. It will always be a unique number within your
// application.
nm.notify(0, notif);
}catch(Exception e){
e.getMessage();
}
}
}
And I declare my Service in my project manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".ServiceDemoActivity"
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=".ServiceExample"></service>
</application>
</manifest>
Here's my class for starting and stopping the Service:
package com.demo;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class ServiceDemoActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
}
private Intent inetnt;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
inetnt=new Intent(this,ServiceExample.class);
startService(inetnt);
break;
case R.id.stop:
inetnt=new Intent(this,ServiceExample.class);
stopService(inetnt);
break;
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
//
}
}
Here's my layout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StartService"
android:id="#+id/start"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StopService"
android:id="#+id/stop" />
</LinearLayout>

In order to have your notification always present, you'll want to set these two flags:
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
Note that while setting your Service to be in the foreground will also get you an ongoing event, that is a very inappropriate thing to do unless you truly do need your Service to run in the foreground. A music player is a good example of an app that should do that -- the user has an expectation that their music will play without interruption, even when doing many other things with the device.
Most Services, however, can afford to be temporarily stopped by the system when memory is low, and then restarted automatically when memory is available again. So the correct way to think about it is to separate the two ideas.
If you want your notification to always be visible, use the two flags I mentioned.
If you happen to also need your Service to run in the foreground, you can and should call Service.startForeground(), but don't think of this as a way to get an ongoing notification.

If you want your application to be present on the status bar at all times, you have to write a service and call startForeground(id, notification) in the onStart(...) and onStartCommand(...) methods and respectively call the stopForeground() method in the onDestroy() method of the service.
The id is an integer you can assign to the notification and notification is a Notification object (you can read about it more here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html).
This way as long as your service is running, the status bar notification will show.
Notification notification = new Notification(R.drawable.statusbar_icon,
"Rolling text on statusbar", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, YourActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,
"Notification title", "Notification description", contentIntent);
startForeground(1, notification);
You can put this code in the service's onStart(...) and onStartCommand(...) methods.
Also you can read more on services here: http://developer.android.com/reference/android/app/Service.html

Just use below code to always show notification bar.
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("Call Recorder")
.setAutoCancel(false);
Notification notification = builder.getNotification();
notification.flags |= Notification.FLAG_NO_CLEAR
| Notification.FLAG_ONGOING_EVENT;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);

Here's example using NotificationCompact.Builder class which is the recent version to build notification.
private void startNotification() {
//Sets an ID for the notification
int mNotificationId = 001;
// Build Notification , setOngoing keeps the notification always in status bar
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ldb)
.setContentTitle("Stop LDB")
.setContentText("Click to stop LDB")
.setOngoing(true);
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Build the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}

Related

Run Android Notifications when App is closed without GCM/Firebase

I am working on an App where I want to show Push Notifications. Please note that since it is my client's requirement NOT to use any third party services, so using GCM/Firebase is out of question.
I am successfully able to show the notification from Service using the below code.
public class SendNotificationService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
CharSequence title = "Notification Title";
CharSequence message = "This is a test notification.";
Drawable drawable= ContextCompat.getDrawable(this,R.drawable.brand_icon_color);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.brand_icon_small_color)
.setLargeIcon(bitmap)
.setAutoCancel(true)
.setContentTitle(title)
.setOngoing(false);
mBuilder.setContentText(message);
mBuilder.setTicker(message);
mBuilder.setWhen(System.currentTimeMillis());
NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
mBuilder.setContentIntent(pendingIntent);
notificationManager.notify(0, mBuilder.build());
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
}
}
I am starting this service through my AsyncTask onPostExecute method.
Intent intentService = new Intent(context, SendNotificationService.class);
context.startService(intentService);
I created this following a number of tutorials and found that if I will go to my Running Apps in Android Settings, I will be able to see this service running. But I was unable to locate any such service.
Now the problem is when I close my Application, the notification also disappears. I want it to stay until the user takes any action.
In addition to this, I want this service to start with phone startup even if the app is not started.
1) Add the permission to the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) Add a receiver to the manifest to run on boot:
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In MyBroadcastReceiver.java:
package com.example;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}

Can't swipe-delete a notification from service

I have a service which downloads data, runs in a separate process (so that it doesn't die/restart when the app is closed) and shows a notification with it's progress. I want to be able to stop the service if the user swipe-deletes the notification, but have so far been unable to do it. Relevant code below:
DatabaseDownloadService.java
public class DatabaseDownloadService extends Service
{
private final static int NOTIFICATION_ID = 1337;
private final static String NOTIFICATION_DISMISSAL_TAG = "my_notification_dismissal_tag";
private NotificationManager mNotificationManager;
#Override
public void onCreate()
{
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getNotification("Downloading database...");
startForeground(NOTIFICATION_ID, notification);
startDownloadingStuff();
}
private Notification getNotification(String text)
{
NotificationDismissedReceiver receiver = new NotificationDismissedReceiver();
registerReceiver(receiver, new IntentFilter(NOTIFICATION_DISMISSAL_TAG));
Intent intent = new Intent(this, NotificationDismissedReceiver.class);
PendingIntent deleteIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, intent, 0);
return new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentText(text)
.setDeleteIntent(deleteIntent)
.build();
}
public class NotificationDismissedReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
int notificationId = intent.getExtras().getInt(NOTIFICATION_DISMISSAL_TAG);
Toast.makeText(context, "Download cancelled", Toast.LENGTH_SHORT).show();
// Do more logic stuff here once this works...
}
}
}
AndroidManifest.xml
<application
... properties and activities go here...>
<service
android:name=".DatabaseDownloadService"
android:process=":dds_process"
android:enabled="true"/>
<receiver
android:name="com.myapp.DatabaseDownloadService$NotificationDismissedReceiver"
android:exported="false"/>
</application>
As far as I can tell, the .setDeleteIntent() should make the notification swipe-deletable, which should then send a broadcast, which should then be caught by my NotificationDismissedReceiver. However, as it stands, I can't even swipe-delete the notification, and I never see the "Download cancelled" Toast...
You can call to stop the service from foreground, passing false, means not remove the notification. For Android N and above, you can pass STOP_FOREGROUND_DETACH also.
stopForeground(false);
After that you can stop the service by yourself also.
stopSelf();
Instead of using startForeground(), use :
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify("tag", NOTIFICATION_ID, notification);

Displaying push notification while app is not open

I'm trying to create notifications for my app that sends notifications when a certain task is due. Each task has a deadline time so I want to send a notification for each task when their deadline has passed.
My main class is called RecyclerViewDemoActivity and inside the onCreate() I have this:
public void setNotification()
{
Intent intent=new Intent(this,NotificationClass.class);
AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent= PendingIntent.getService(this, 0, intent, 0);
// hardcoding the time just for this example
manager.set(AlarmManager.RTC_WAKEUP,1449208683000,pendingIntent);
}
and I have a NotificationClass that looks like this:
public class NotificationClass extends Service {
#Override
public void onCreate()
{
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grokkingandroid.samplesapp.samples.recyclerviewdemo" >
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<application
android:name="com.teamvallartas.autodue.RecyclerViewDemoApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.teamv.RecyclerViewDemoActivity"
android:label="#string/app_name"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I looked at this resource for the code above and also Vogella's resource on notifications but I don't know why this is not working.
Check if onCreate of Service class is getting called. If it is, then the problem is "You placed your code at wrong method.".
You need to move code into onStartCommand(Intent intent, int flags, int startId).
Like
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
Notification nBuilder= new Notification.Builder(this)
.setContentTitle("This task is due!")
.setContentIntent(pIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1,nBuilder);
// If we get killed, after returning from here, restart
return START_STICKY;
}
Update your manifest and add this entry to it
<service android:name=".NotificationClass" />
you can do it in this way ,
1st > create one local broadcast receiver ,
inside onReceive() method , put your code stuff for generate notification
,that is your setNotification() method .
2nd > you just register that broadcast receiver inside onCreate() and unregister it inside onPause() or onDestory() method . like this ...
ReceiverActivity.java
public void onCreate(Bundle savedInstanceState) {
...
// Register your broadcast receiver here ...
// with actions named "custom-event-name"...
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
protected void onDestroy() {
// Unregister your receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
//here comes our receiver ...
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//called setNotification() here ...
}
};
Now let suppose you want to generate notification on click event of your button then fire intent like this,
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "Its me!!!!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
your **setNotification()**should be like this ..
public void Notification(Context context, String message) {
// Set Notification Title
String strtitle = context.getString(R.string.notificationtitle);
// Open NotificationView Class on Notification Click
Intent intent = new Intent(context, NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", message);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.logosmall)
// Set Ticker Message
.setTicker(message)
// Set Title
.setContentTitle(context.getString(R.string.notificationtitle))
// Set Text
.setContentText(message)
// Add an Action Button below Notification
.addAction(R.drawable.ic_launcher, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}

how to show android notification and application icon

I have a service running, and would like to send a notification. Too bad, the notification object requires a context, like an Activity, and not a service.
Do you know any way to by pass that ? I tried to create an Activity for each notification bu it seems ugly, and I can't find a way to launch an Activity without any view.
i also want to sent my application icon to notification to show icon top of screen
Here is a working code , which creates a notification from a service itself.
hope it will help you,
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//We get a reference to the NotificationManager
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Reminder";
Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Medicine!";
String MyNotificationText = "Don't forget to take your medicine!";
Intent MyIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}

Coverting iOS notifications to Android notifications

Trying to convert my iOS app to android, I know I can't port it so I wrote it from scratch
How can I covert this notification to Android Java code?
-(IBAction)turnon {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:28];
[comps setMonth:9];
[comps setYear:2012];
[comps setHour:8];
[comps setMinute:25];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *fireDate = [gregorian dateFromComponents:comps];
UILocalNotification *alarm = [[UILocalNotification alloc] init];
alarm.fireDate = fireDate;
alarm.repeatInterval = NSDayCalendarUnit;
alarm.soundName = #"msl.aiff";
alarm.alertBody = #"This is a message..";
alarm.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:alarm];
I've searched the web for like 4 hours now and I think this is simple for an Android developer but since I just started I just don't have any idea how to do this.
Any help is really appreciated!
This is what your looking for:
You can use the alarm manager to show notifications at specific times, even when your app is not running at all.
http://developer.android.com/reference/android/app/AlarmManager.html
Everyday notifications at certain time
This one is useful to:
Using Alarmmanager to start a service at specific time
Edit see comments:
You can the AlarmManager for this, first create you self some kind of reciever.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, MyService.class);
context.startService(dailyUpdater);
Log.d("AlarmReceiver", "started service");
}
}
Than you need to create the service which is going to show the notifications
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = 546;
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return START_STICKY;
}
#Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Toast.makeText(this, "show notification", Toast.LENGTH_SHORT).show();
//notification code here
}
}
And finally you need to set the alarm:
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 30);
Intent open = new Intent(context, AlarmReceiver.class);
open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, open, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, 10000, pendingIntent);
}
And before you make a test run add your Receiver and Service to your manifest file:
<service android:name=".MyService"></service>
<receiver android:name=".AlarmReceiver"></receiver>
A copy paste with some minor changes from the Android developer site
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
// Sets an ID for the notification, so it can be updated
int mId= 1;
mNotificationManager.notify(mId, mBuilder.build());

Categories

Resources