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);
Related
I put here my code...
I explain my problem..
when I create a notification, it appears to me immediately even if I enter a specific time to make it appear.
at that time instead opens automatically as if i push on notification.
can you tell me how I can play it at the time that i inserted?
thanks
import java.util.Calendar;
import java.util.StringTokenizer;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
public class Allarm {
private Context context;
public Allarm(Context context) {
this.context = context;
}
public void createAlarm(String rip,String title,String object,String dati) {
String day= "01";
String month= "01";
String year= "2014";
String hour= "00";
String minute = "02";
String date = day+"/"+month+"/"+year+" "+hour+":"+minute;
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(Integer.valueOf(year), Integer.valueOf(month),
Integer.valueOf(day), Integer.valueOf(hour),
Integer.valueOf(minute), 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent =new Intent(context, NotificationReceiverActivity.class);
intent.putExtra("dati", dati);
intent.setData(Uri.parse("content://"+date));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
context)
.setWhen(myAlarmDate.getTimeInMillis())
.setContentText(object)
.setContentTitle(title)
.setSmallIcon(R.drawable.avvio)
.setAutoCancel(true)
.setTicker(title)
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
Notification notification=notificationBuilder.build();
alarmManager.set(AlarmManager.RTC_WAKEUP,
myAlarmDate.getTimeInMillis(), pendingIntent);
notificationManager.notify((int) myAlarmDate.getTimeInMillis(), notification);
}
}
The method NotificationManager.notify(int id, Notification notification) posts the notification immediately. The first argument is an id you specify and not the time the notification should be displayed.
You could use the AlarmManager to schedule a notification.
I am using this notifications code:
package com.example.mega;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Tech";
CharSequence message = "Check out our NEW COLLECTION !!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.icon,
"Check out our NEW COLLECTION !!" , System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
}
}
As you see I haven't yet added AlarmManager since I have no experience using it ,I am new to android.What should I add to the code to have show the notification every 24 hours ??
Calendar calendar = Calendar.getInstance();
// 8.00 (8 AM)
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0 , new Intent(context, Your_Class.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
This sets an alarm everyday at 8.00 AM
Or you can use https://github.com/commonsguy/cwac-wakeful. Take a look at the documentation on the link.
Take a look at this: Fire notification at every 24 hours and at exact time of 8 AM
And this: http://blog.blundellapps.com/notification-for-a-user-chosen-time/
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());
I am trying to start code inside an activity at regular intervals using Alarm manager. I have looked at various examples on here but they have not really helped.
For testing purposes, all I am trying to do is pop up a toast at 10 second intervals, but nothing seems to be happening at all. Please help guys!
I have this in the manifest (also declarations for all three activities):
<receiver android:name=".receiver.AlarmReceiver"></receiver>
Code from main activity, in OnCreate:
//
// Setting up the Alarm Manager
//
Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long timerInterval = 10 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent);
//finish();
AlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show();
Intent scheduledIntent = new Intent(context, MyService.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
MyService.java:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Toast.makeText(getBaseContext(),"test message.",
Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Your activity is not showing, because you are calling startActivity() on an Intent that identifies a Service. You should see warnings related to this in LogCat.
I humbly suggest that you use LogCat yourself, via the Log class, for logging background operations, rather than attempting to use a Toast.
test this code:
private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}
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);
}
}