how to show android notification and application icon - android

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();
}
}

Related

Intent Filter Pending Intent , Broadcast Reciever and Notification Manager

I'm working hard to understand these concepts how they are working.
can someone explain these concepts to me??
here is the code I want to understand
Intent intent = new Intent();
intent.setAction("com.example.akshay.proximityalertexample2");
PendingIntent intent1 = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(LAT, LONG, 200, -1, intent1);
IntentFilter filter = new IntentFilter("com.example.akshay.proximityalertexample2");
registerReceiver(new ProximityAlert(), filter);
Broadcast class file
package com.example.akshay.proximityalertexample2;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import android.widget.Toast;
/**
* Created by Akshay on 9/18/2015.
*/
public class ProximityAlert extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Toast.makeText(context, key, Toast.LENGTH_SHORT).show();
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.e(getClass().getSimpleName(), "entering");
} else {
Log.e(getClass().getSimpleName(), "exiting");
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Notification notification = createNotification();
PendingIntent pendingIntent = PendingIntent.getActivity(context , 0 , null , 0 );
notification.setLatestEventInfo(context,"Proximity Alert!!","You Are Near the Point of intereste " ,pendingIntent);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.ledOffMS = 1500;
notification.ledOnMS = 1500;
return notification;
}
}
Please explain me the working of these concepts..
any help would mean me alot
thanks a lot
This is a really old thread, but I figured for my own learning and the benefit of anyone else arriving on this thread I'd take a shot at it.
In the first snippet, you are creating an intent that doesn't do anything, and wrapping it with a pendingIntent, to be called by the app later at some point. The intent filter serves to let other apps (mainly the receiver in this case) know what kind of intent are we dealing with (it's a poor example, would've personally gone with something like PROX_ALERT_INTENT). We add a proximity alert, and register the intent with our Receiver class.
In the Receiver class, We first define the boolean key that determines if we've stepped in the proximity alert radius or not. Then we fetch the key from the broadcasted intent (its passed automatically), following which we check if the user has indeed entered the proximity alert area.
If he has, we create a notification that has a pending intent attached (which in this case does nothing but could launch a new activity for example), and launch the notification.
Note that this method of notification building has deprecated, have to use the builder now.

Ignoring notification with

Edit: It's fixed even though my code isn't perfect. I forgot to register this BroadCastReceiver in my Android Manifest file. Face Palm.
I'm having trouble getting my notification to work. It would help if I get some meaningful error message but I have no idea how to debug this.
Here's the code of the broadcast receiver:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ThisDoesNotWork extends BroadcastReceiver{
private Intent myIntent;
private PendingIntent myPending;
private static final int MY_NOTIFICATION_ID = 1;
private final CharSequence text1 = "Text1";
private final CharSequence text2 = "Text2!";
#Override
public void onReceive(Context context, Intent intent) {
myIntent = new Intent(context, MainActivity.class);
myPending = PendingIntent.getActivity(context, 0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
Notification.Builder myNote = new Notification.Builder(context).setTicker(
"Take a Selfie!")
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true).setContentTitle(text1)
.setContentText(text2)
.setContentIntent(myPending);
NotificationManager mNotify = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Log.i("Receiver", "Notification created.");
mNotify.notify(MY_NOTIFICATION_ID,myNote.getNotification());
Log.i("Receiver", "Notification sent.");
}
}
My program compiles but this notification gets ignored.
The error message I get is: Ignoring notification with icon==0; Notification(contentView =null vibrate=null...
Can anyone bring me 1 step closer to a solution?
Per the required notification contents, you must include:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
It appears you are missing the content title, causing your notification to get ignored.

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());

Always show service in notification bar

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());
}

Wrong timestamp in Android Notification

In the bottom right corner of my standard Android notification I will not see time (eg 12:00) rather than a pattern like that: 11/1/16. Always 3 numbers diveded by "/". Anybody know the problem?
I don't khow, how you make your notification but i think you should use : System.currentTimeMillis()
Example :
package com.test;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class TestActivity extends Activity {
private NotificationManager notificationManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification("My notification",android.R.id.text1);
}
private void showNotification(CharSequence text, int idNotify) {
Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
Intent intent = new Intent();
intent.setClassName("com.test","com.test.TestActivity");
PendingIntent contentIntent = PendingIntent.getActivity(TestActivity.this, 0,intent,0);
notification.setLatestEventInfo(this, "My Notification",text, contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(idNotify, notification);
}
}

Categories

Resources