I'm using the following code to generate a mediaPlayer notification:
package com.app1.notificationtemplate;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
public class NotificationGenerator {
public static final int NOTIFICATION_ID_OPEN_ACTIVITY = 9;
public static final String NOTIFY_PREVIOUS = "com.a.b.previous";
public static final String NOTIFY_DELETE = "com.a.b.delete";
public static final String NOTIFY_PAUSE = "com.a.b.pause";
public static final String NOTIFY_PLAY = "com.a.b.play";
public static final String NOTIFY_NEXT = "com.a.b.next";
public static void openActivityNotificaton(Context context) {
NotificationCompat.Builder nc = new NotificationCompat.Builder(context,
MainActivity.channelID);
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.mipmap.ic_launcher);
nc.setAutoCancel(true);
nc.setContentTitle("Notification Demo");
nc.setContentText("Click please");
nm.notify(NOTIFICATION_ID_OPEN_ACTIVITY, nc.build());
}
public static void customBigNotification(Context context){
final RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.big_notification);
NotificationCompat.Builder nc = new NotificationCompat.Builder(context, MainActivity.channelID);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.drawable.play);
nc.setAutoCancel(true);
nc.setCustomBigContentView(expandedView);
nc.setContentTitle("MusicPlayer");
nc.setPriority(NotificationCompat.PRIORITY_MAX);
nc.setContentText("Control AUdio");
//expandedView.setTextViewText(R.id.text_song_name,"Adele");
setListeners(expandedView, context);
Notification notification = nc.build();
notification.flags = NotificationCompat.FLAG_ONGOING_EVENT|NotificationCompat.FLAG_FOREGROUND_SERVICE
| NotificationCompat.FLAG_NO_CLEAR|NotificationCompat.FLAG_BUBBLE ;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
nm.notify("newNotif", 1, nc.build());
}
public static void setListeners(RemoteViews view, Context context){
Intent previous = new Intent(NOTIFY_PREVIOUS);
Intent delete = new Intent(NOTIFY_DELETE);
Intent pause = new Intent(NOTIFY_PAUSE);
Intent next = new Intent(NOTIFY_NEXT);
Intent play = new Intent(NOTIFY_PLAY);
PendingIntent pPrevious = PendingIntent.getBroadcast(context, 0,
previous, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPrevious, pPrevious);
PendingIntent pDelete = PendingIntent.getBroadcast(context, 0,
delete, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnDelete, pDelete);
PendingIntent pPause = PendingIntent.getBroadcast(context, 0,
pause, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPause, pPause);
PendingIntent pPlay = PendingIntent.getBroadcast(context, 0,
play, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnPlay, pPlay);
PendingIntent pNext = PendingIntent.getBroadcast(context, 0,
next, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.btnNext, pNext);
}
}
I have custom notification views (RemoteViews) setup for the notification as well.
but, when I click play, I'm not sure how to update the play view to a pause view. Currently, I'm just setting the visibility of the play button to gone. But, is turning on and off the visibility turnwise the only option? And how do I do that anyways(the tutorial I've followed doesn't really show this). But, I think it'd be better if we could replace the image in the button which would avoid possible blinking or flickering. I've also gotta update the Remote view's artist and song Title name, but have no idea to do so. Please tell me how to update views in the RemoteView according to user interaction
Also, to communicate from the notification to the Service is using Broadcasts the only option? What other options do I have?
You need to create a new notification with the updated data and use NotificationManager to update it. No need to start service again. You have a running foreground service, all you have to do is update your UI via notify.
So in your Broadcast Receiver call your openActivityNotificaton() function with updated data, according to what view was clicked inside the notification. You can have one Receiver with a unique action for each view click, and update notification accordingly. I tested and it does not cause a blink, the notification is updated smoothly.
The code for your Receiver would be something like this:
const val NOTIFICATION_TITLE_INTENT_ACTION = "notification_title_intent_action"
const val NOTIFICATION_ARROW_INTENT_ACTION = "notification_arrow_intent_action"
class NotificationInteractionReceiver : BroadcastReceiver() {
private lateinit var notificationsFactory: NotificationFactory
override fun onReceive(context: Context, intent: Intent) {
notificationsFactory = NotificationFactory(context)
// Update title according to what button was clicked
val newTitle = when (intent.action) {
NOTIFICATION_TITLE_INTENT_ACTION -> "title clicked"
else -> "arrow clicked"
}
// Pass new title to class responsible for showing notification
notificationsFactory.showNotification(context, s)
}
companion object {
fun getIntent(context: Context, action: String): Intent {
val intent = Intent(context, NotificationInteractionReceiver::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
intent.action = action
return intent
}
}
}
Related
I am trying to add a notification feature to my application. I want it to run a notification or action at the same time, every day. I have this code for my notification right now:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 45612;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
// Build the notification
notification.setSmallIcon(R.drawable.icon);
notification.setTicker("Brook Betterment Plan");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Brook Betterment Plan");
notification.setContentText("Don't forget to enter your daily stats! ");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
// Builds notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
}
Thanks! Hope someone knows the answer. Also, I was hoping it wouldn't need any additional Activitys or Java class's.
Alarm Manager
public static void startAlarmBroadcastReceiver(Context context) {
Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Alarm Broadcast Receiver
In AndroidManifest, just define the class as
<receiver android:name=".AlarmBroadcastReceiver" >
</receiver>
And code will be like
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
void showNotification(Context context) {
String CHANNEL_ID = "your_name";// The id of the channel.
CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, TestActivity.class);
Bundle bundle = new Bundle();
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setContentTitle("Title");
} else {
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle("Title");
}
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("Your Text");
mBuilder.setAutoCancel(true);
mNotificationManager.notify(1, mBuilder.build());
}
}
Create a class that will generate notification, like LocalNotification
Add the code you have in on create in that class under a method like showDailyNotification
Now use JobScheduler and schedule a job for every 24 hours, when the job is started call this method in LocalNotification
Make LocalNotification a singleton class.
BTW don't forget to use notification channel because otherwise it will not work on Oreo and above devices.
Hi i am making a habit tracker app and when a new habit is created by user i call sendNotification() method for calling notifications at time specified by user.I want to show these notifications everyday at time specified by user.
Now notifications are showing up when app is running or when app is minimized but when i close app (not from settings) notifications are shown.
Here's my code:
private void sendNotification(){
NotificationReceiver.setupAlarm(this, notificationCalendar);
}
public class NotificationReceiver extends WakefulBroadcastReceiver {
public NotificationReceiver() {
}
public static void setupAlarm(Context context, Calendar notificationCalendar) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
startWakefulService(context, serviceIntent);
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationReceiver.class);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
return new Intent(context, NotificationIntentService.class);
}
#Override
protected void onHandleIntent(Intent intent) {
try{
processStartNotification();
}finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Habit Time")
.setContentText("Hey time for your habit")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(alarmSound)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
}
}
//Manifest file
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".notification.NotificationReceiver"/>
<service
android:name=".notification.NotificationIntentService"
android:enabled="true"
android:exported="false"/>
The notification won't show until you make a background service for them. Create a background service and send broadcast from that service, this service will keep running weather your app is running or not. You can check this detailed answer.
Make a NotificationService class and extend it like below.
public class NotificationService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
/* send your notification from here, in timely manner */
}
}
Start is from your activity like this
Intent i = new Intent("com.example.package.NotificationService");
startService(i);
This code is written to give you an idea. I didn't test it.
Try the following code: it creates an alarm for a specific time in a day using alarmanager and repeat it daily...
Declare
Calendar cal_alarm;
Now set the calender object for specific time to alarm
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm a");
String time=""21 12 2016 8:10 AM"
cal_alarm = Calendar.getInstance();
cal_alarm.setTime(dateFormat.parse(time));
Set the alarm
public void set_alarm() {
Calendar calNow = Calendar.getInstance();
long current_time = calNow.getTimeInMillis();
Log.d("ALARM CALENDER VALUES", cal_alarm.toString());
long alarm_time_in_millis = cal_alarm.getTimeInMillis();
//check if time is alreday passed or not
if (alarm_time_in_millis > current_time) {
new Alarm_task(getApplicationContext(), cal_alarm).run();
}
public class Alarm_task implements Runnable {
// The date selected for the alarm
private final Calendar cal;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
long alarm_time2;
int _id;
public Alarm_task(Context context, Calendar cal) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.cal = cal;
this._id = (int) System.currentTimeMillis();
alarm_time2 = cal.getTimeInMillis();
//Toast.makeText(getActivity(), alarm_time2 + " ", Toast.LENGTH_SHORT).show();
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent i = new Intent("com.package_name");
i.setAction("com.package_name");
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getApplicationContext(), _id, i, PendingIntent.FLAG_UPDATE_CURRENT);
/** Converting the date and time in to milliseconds elapsed since epoch */
long alarm_time = cal.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time each day*/
am.setRepeating(AlarmManager.RTC_WAKEUP, alarm_time, AlarmManager.INTERVAL_DAY, operation);
}
}
Now in manifest define an explicit activity which handle the alarm intent and show popup dialog and notification during alarm time
<activity
android:name=".Prereminder"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
//same as your alarm task
<action android:name="com.package_name" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Now in your Prereminder.java
public class Prereminder extends FragmentActivity {
String msg = "Helloo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
sendNotification();
/** Creating an Alert Dialog Window */
Reminder_alert alert = new Reminder_alert();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "Reminder_alert");
}
private void sendNotification() {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
//handle notification on click
Intent myintent = new Intent(this, Home_page.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_small)
.setContentTitle("Alarm")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Now your Reminder_alert class show the popup dialog during alarm:
public class Reminder_alert extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("ALARM ON");
/** Setting the content for the alert dialog */
builder.setMessage("WAKE UP NOW");
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
/** Creating the alert dialog window */
return builder.create();
}
/**
* The application should be exit, if the user presses the back button
*/
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
}
1- in simple way first use this function to create alarm
private void createAlarm(Date start_alarm_date, String schedual_type ,String schedule_id){
AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, PushLocalNotification.AlarmReceiver.class);
intent.setAction("Your_Action_Name"); //this action you will use later
intent.putExtra("Extra", any_extra_you_want_add);// remove if you want add extra
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at specific date
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// repeat it "daily":
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
2- create IntentService and make your receiver extend BroadcastReceiver
public class PushLocalNotification extends IntentService {
private NotificationManager mNotificationManager;
private String mScheduleID;
NotificationCompat.Builder builder;
public PushLocalNotification() {
super("pushLocalNotification");
}
#Override
protected void onHandleIntent(Intent intent) {
// call create local notification here
}
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("Your_action_Name")) {
// call service here.
Intent sendIntent = new Intent(context, PushLocalNotification.class);
sendIntent.putExtra("Extra_name", intent.getStringExtra("Previos_extra_you_add_before"));
context.startService(sendIntent);
}
}
}
private void createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Create Intent to launch this Activity again if the notification is clicked.
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(intent);
// Sets the ticker text
builder.setTicker(getResources().getString(R.string.custom_notification));
// Sets the small icon for the ticker
builder.setSmallIcon(R.drawable.ic_stat_custom);
// Cancel the notification when clicked
builder.setAutoCancel(true);
// Build the notification
Notification notification = builder.build();
// Inflate the notification layout as RemoteViews
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
// Set text on a TextView in the RemoteViews programmatically.
final String time = DateFormat.getTimeInstance().format(new Date()).toString();
final String text = getResources().getString(R.string.collapsed, time);
contentView.setTextViewText(R.id.textView, text);
/* Workaround: Need to set the content view here directly on the notification.
* NotificationCompatBuilder contains a bug that prevents this from working on platform
* versions HoneyComb.
* See https://code.google.com/p/android/issues/detail?id=30495
*/
notification.contentView = contentView;
// Add a big content view to the notification if supported.
// Support for expanded notifications was added in API level 16.
// (The normal contentView is shown when the notification is collapsed, when expanded the
// big content view set here is displayed.)
if (Build.VERSION.SDK_INT >= 16) {
// Inflate and set the layout for the expanded notification view
RemoteViews expandedView =
new RemoteViews(getPackageName(), R.layout.notification_expanded);
notification.bigContentView = expandedView;
}
// START_INCLUDE(notify)
// Use the NotificationManager to show the notification
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0, notification);
}
}
3- final step don't forget to declare service and receiver inside manifest file
<receiver
android:name=".PushLocalNotification$AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="Your_Action_name:)" />
</intent-filter>
</receiver>
<service android:name=".PushLocalNotification" />
be patient and have fun :)
Create a method which contains your Code where you will define your Time or at what time you want to show the notification.This method need to be called from where you want user to ask for notification.
public void getNotification () {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 00);
if (now.after(calendar)) {
Log.d("Hey","Added a day");
calendar.add(Calendar.DATE, 1);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Create a Notification_receiver class which is going to extend Broadcast Receiver here you are going to define your Channel Id as it is perfectly working for API 25 and above this the Notification_receiver class:
import android.app.Notification;
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.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
//Created By Prabhat Dwivedi
public class Notification_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("Your App Name",
"You app Package Name",
NotificationManager.IMPORTANCE_HIGH);
String channel_Id = channel.getId();
CharSequence channel_name = channel.getName();
Log.e("Notification_receiver", "channel_Id :" + channel_Id);
Log.e("channel_name", "channel_name :" + channel_name);
channel.setDescription("Make entry of today's spending now");
notificationManager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.yourapp_logo)
.setChannelId("Your app Name is your Channel Id")
.setContentTitle("Your title")
.setContentText("Your Description")
.setAutoCancel(true);
//nder this you will find intent it is going to define after clicking notification which activity you want to redirect
Intent repeatingIntent = new Intent(context, HomePage.class);
pendingIntent = PendingIntent.getActivity(context, 100, repeatingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
notificationManager.notify(100, builder.build());
}
}
Kindly also add the Notification receiver inside AndroidManifest.xml file
<receiver android:name=".Notification_receiver"/>
Hi i got stock in this point wherein "setLatesEventInfo" has an error. i know that setLatestEventInfo doesnt run on API 23 and up. can someone help me on how to make this code run ? i mean alternative way , same function but different coded. this is a receiver function. i am doing a notification on my Mainactivity. The only error here is the receiver ,i tried the builder notification , but since this is a receiver ,builder cant apply
Receiver.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by my pc on 12/1/2015.
*/
public class Receiver extends BroadcastReceiver {
private static final Object ACTION = "MyNotification";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action)) {
//do what you want here
Variables.numMessages++;
generateNotification(context,"MyNotification");
}
}
private void generateNotification(Context context, String message) {
long when = System.currentTimeMillis();
int icon = R.drawable.ic_od_icon_24dp;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
// String subTitle = context.getString(R.string.app_name);
String subTitle = "some text";
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("content", message);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.setLatestEventInfo(context, title, subTitle, intent);
//To play the default sound with your notification:
//notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
MainActivity.java
public class MainActivity extends Activity {
int NOTIFICATION_ID = 1;
int LED_ON_MS = 200;
int LED_OFF_MS = 600;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onGenNoti(View v) {
// Check readCount
Variables.readCount = Variables.numMessages;
PendingIntent pIntent =
PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MainActivity.class), 0);
if (Variables.numMessages > 0) {
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("You Have " + Variables.numMessages + " message")
.setContentTitle("test")
.setContentText("")
.setSmallIcon(R.drawable.ic_od_icon_24dp)
.setContentIntent(pIntent).getNotification();
noti.defaults |= Notification.DEFAULT_SOUND;
noti.defaults |= Notification.DEFAULT_VIBRATE;
noti.ledARGB = Color.BLUE;
noti.ledOnMS = LED_ON_MS;
noti.ledOffMS = LED_OFF_MS;
noti.flags = Notification.FLAG_SHOW_LIGHTS;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, noti);
}
}
}
Now you have to generate your notification like this
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context);
// set intent so it does not start a new activity
Notification notification = builder
.setContentIntent(yourPendingIntent)
.setSmallIcon(icon)
.setWhen( System.currentTimeMillis();)
.setContentTitle(title)
.setContentText(message).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notifId, notification);
I am getting "The method getSystemService(String) is undefined for the type AlarmManagerBroadcastReceiver" error. I even tried to put getActivity() before it but it was of no help.
code for AlarmManagerBroadcastReceiver.java
package com.archana.pocketfriendly;
import java.text.Format;
import java.text.SimpleDateFormat;
import android.app.AlarmManager;
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.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
MediaPlayer alarm;
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
alarm = MediaPlayer.create(context, R.raw.alarm);
alarm.start();
msgStr.append("Do you want to enter the expenses?\nIgnore if already done!");
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Vibrator vib=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(2000);
// notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.settings)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainMenu.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(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainMenu.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); //error in this `enter code here`line.
mNotificationManager.notify(0, mBuilder.build());
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 86400 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Please let me know if any other information is required.
Just like your other calls to getSystemService, you need to perform it on a context object:
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
I want to cancel/delete the notification after I click the addAction.
However it's not working. The notification is still there after the click.
I'm pretty sure this worked in an other project.
Can anyone see a stupid error I made, why its not working?
Actual code:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context){
String onderwerp = ("Medicatietijd");
String name = ("Het is tijd om je medicitie in te nemen.");
// Geluid notificatie
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Test.class), 0);
// De notificatie
Notification mNotification = new Notification.Builder(context)
.setContentTitle(onderwerp)
.setContentText(name)
.setSmallIcon(R.drawable.ninja)
.setSound(soundUri)
.addAction(R.drawable.ja, "Ja, ik heb ze ingenomen.", contentIntent)
.setAutoCancel(true)
.build();
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.vibrate = new long[]{100, 200, 100, 500};
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
Solution:
In test activity OnCreate added this:
NotificationManager notificationManager
= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
If you decided to use Test activity to receive the intent of your addAction call, then you must cancel notification when you receive the intent in the activity.
I also recommend that you add requestCode for the intent.
Here is the code :
to set the requestCode modify this :
static final int REQ_CODE = 101; // some number
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, REQ_CODE,
new Intent(context, Test.class), 0);
to Handle intent in activity and dismiss the notification, in Test activity class :
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE) {
// dismiss notification
notificationManager.cancel(0);
// handle your action
// ...
}
}
Hope that helps