notificationID cannot be resolved to a variable - android

I have just started studying Android, I have limited java knowledge but am semi capable with c/c++ objective C etc... I am currently working through a p2pwrox ebook called Beginning Android Application Development that I brought, however I am coming unstuck with the "Try it out: Display Notifications on the status bar" on pg73.
I have managed to write it all out sweet and am getting used to the android sdk and eclipse ide, however I have got this error in my NotificationActivity.java file shown below that I just don't know how to fix.
package com.androidtestingfun.www;
import android.app.Activity;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class NotificationsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.btn_displaynotif);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
displayNotification();
}
});
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID); //-----the second parameter here is getting an error
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
//---100ms delay, vibrate for 250ms, pause for 100ms and then vibrate for 500ms---
notif.vibrate = new long[] {100, 250, 100, 500};
nm.notify(notificationID, notif);//-----the first parameter here is getting an error
}
}
Any ideas that could hear me would be greatly appreciated, I have tried cleaning my build but that didnt do anything to help.

You do not have a variable called notificationID.
Add this variable to the class, see snippet example:
public class NotificationsActivity extends Activity {
private static final int notificationID = 1234;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// ........
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
notif.vibrate = new long[] {100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}

Related

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

android no notification popup in statusbar

there're two problems here. I try to let user select a specific time to make app reminder users to use app. Once user set up a time say 8:00 pm. The notification should pop up every day. However, After I used
"NotificationManager" and "Notification"
first of all, there's nothing pop-up. For example, now is 1:19 am in AU, then, i set-up this app to 1:20 am to display the notification in the status bar as a test.
Secondly, if in my TabBar class i use
nm.cancel(getIntent().getExtras().getInt("NotifID"));
It will get a null pointer exception
Here is my code:
TabBar.class
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancel(getIntent().getExtras().getInt("NotifID"));
Notification.class
package com.example.tabpro;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
public class SettingNotification extends Activity{
TimePicker timePicker;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_notification);
Button btnset = (Button) findViewById(R.id.btnSetAlarm);
btnset.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
timePicker = (TimePicker) findViewById(R.id.timePicker_settime);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
Intent i = new Intent("com.example.tabpro.DisplayNotification");
Intent i2 = new Intent(SettingNotification.this, TabBar.class);
i.putExtra("NotifID", 1);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0, i, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
startActivity(i2);
}
});
}
}
DisplayNotification.class
package com.example.tabpro;
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 DisplayNotification extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
int notifID = getIntent().getExtras().getInt("NotifID");
Intent i = new Intent("com.example.tabpro.TabBar");
i.putExtra("NotifID", notifID);
PendingIntent detailsIntent = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.ic_launcher, "Time's up!", System.currentTimeMillis());
CharSequence from = "AlarmManager - Time's up!";
CharSequence message = "This is your alert, courtesy of the AlarmManager";
notif.setLatestEventInfo(this, from, message, detailsIntent);
finish();
}
}
You need to call notify() on your NotificationManager to actually show the Notification. Since you never call this method, your Notification is never shown.
Your NullPointerException is likely a different problem. For that, you should do some debugging yourself. First, you need to determine what is null. Then determine why it is null and fix it. In your code, the most likely candidates for causing the NPE in TabBar are nm, getIntent(), and getExtras().
Hope this helps :
You need to call notify() method to display notification in your notification tray of your device.
Below is the code for that:
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context, YourActivity.class), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(yourappname).setWhen(0)
.setAutoCancel(true).setContentTitle(yourappname)
.setContentText(yourmessage).build();
notificationManager.notify(0, notification);

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