Updated MyService #CommonsWare
i have a service that if started will set up an alarm that triggers the notification.
This works fine and the alarms are canceled if the service is stopped.
i am trying to get the notification to open a new activity class but can not get it done
my service class is the following:
package com.example.andtip;
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.support.v4.app.NotificationCompat;
public class BReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, DoSomething.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent("com.example.andtip"),0 );
PendingIntent pi2 = PendingIntent.getActivity(context, 0, myIntent,0 );
myNotification=new NotificationCompat.Builder(context)
.setContentTitle("This is a notification from the example alarm application.")
.setContentText("Notification")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
how should i link the intent pi2 to the notification?
i am trying to get the notification to open a new activity class but can not get it done
You are using getBroadcast() to create your PendingIntent. Use getActivity() to create a PendingIntent that starts up an activity. Make sure that the Intent you put in the PendingIntent is for an activity, and make sure that the activity has its entry in the manifest.
Related
First of all I would like to thank you for clicking on this thread.
Thank you so much for taking your time to read this.
I was planning for the application push a notification on a specific time.
I followed some tutorials online but it seems it doesn't work.
There is no error message on the code itself but no notification is coming out.
Here's my "Notification_receiver.java" file:
package com.example.reviewerapplication;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
public class Notification_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,Chapterchoice.class);
String daily10 = "daily";
intent.putExtra("daily",daily10);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Sample Title")
.setContentText("same message")
.setAutoCancel(true);
if (intent.getAction().equals("MY_NOTIFICATION_MESSAGE")) {
notificationManager.notify(100, builder.build());
}
}
}
This is what is on my MainActivity:
//Daily Notification
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY,21)
calendar.set(Calendar.MINUTE,53)
calendar.set(Calendar.SECOND,0)
val intent2 = Intent(this, Notification_receiver::class.java)
intent2.setAction("MY_NOTIFICATION_MESSAGE")
var pendingIntent = PendingIntent.getBroadcast(this,100,intent2,PendingIntent.FLAG_UPDATE_CURRENT )
var alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent)
I actually got it fixed just now.
my issue is that I used "activity" in the Manifest instead of using "receiver"
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.
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.
Hi I am working on application where I have set the notification on user entered date and time through background service. Now I want to set notification/alarm daily at 6 pm to ask user does he want to add another entry?
How can I achieve this? Should I use the same background service or Broadcast receiver?
Please give me better solution for that and tutorial will be great idea.
Thanks in advance.
First set the Alarm Manager as below
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Create an Broadcast Receiver Class "AlarmReceiver" in this raise the
notifications when onReceive
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, EVentsPerform.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.applogo)
.setContentTitle("Alarm Fired")
.setContentText("Events to be Performed").setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(MID, mNotifyBuilder.build());
MID++;
}
}
and in the manifest file, register receiver for the AlarmReceiver class:
<receiver android:name=".AlarmReceiver"/>
No special permissions are required to raise events via alarm manager.
N.V.Rao's answer is correct, but don't forget to put the receiver tag inside the application tag in the AndroidManifest.xml file:
<receiver android:name=".alarm.AlarmReceiver" />
Year 2021, April
This is a sample code for Daily Repeating Notification On Specific Time(Here 8AM) in Android:-
1.
MainActivity.class
package com.manab.notificationx;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout.activity_main ) ;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 08);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
if (calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.HOUR_OF_DAY, 0);
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
AlarmReceiver.class // This is a broadcast Receiver which is needed for background process
package com.manab.notificationx;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class AlarmReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "this.is.my.channelId";//you can add any id you want
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);//on tap this activity will open
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);//getting the pendingIntent
Notification.Builder builder = new Notification.Builder(context);//building the notification
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//below creating notification channel, because of androids latest update, O is Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"NotificationDemo",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notification);
}
}
NotificationActivity.class //Remember this is an activity, not a class, so create an empty activity.
package com.manab.notificationx;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class NotificationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
}
}
AndroidManifest.xml // Just add the indicated line below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.manab.notificationx">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NotificationX">
<activity android:name=".NotificationActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" />//copy only this line of code
</application>
</manifest>
Let me know if it's working or not
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());