Need some help troubleshooting code that schedules daily notifications - java

I am new to android programming and just started working on my first app recently. I am trying to create a daily notification that a user would get at the same time every day. I've looked through documentation and some tutorials and came up with this. For some reason the code below does not work. It has no errors, runs just fine, but doesn't do the job and I can't seem to find the problem. There is also some code that is responsible for re-scheduling notifications when the device restarts but I don't think the problem lies there since I don't even get the initial notifications.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
AlarmNotificationReciever.Java
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
FLAG_ONE_SHOT );
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Zodiac")
.setContentIntent(pendingIntent)
.setContentText("Check out your horoscope")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
It should basically schedule a notification at 14:45 after pressing the button but for some reason it doesn't.

Since Android Oreo, implicit broadcast receivers won’t work when
registered in the AndroidManifest.xml
To use Implicit Receivers in your application, you need to define them programmatically in your code, using
registerReceiver().
3.Using registerReceiver() we can programmatically register and unregisterReceiver() during the lifecycle of the activity. This way
implicit receivers would only be called when our
activity/application is alive and not at other times.
we working fine:
[public class MainActivity extends AppCompatActivity {
Button show;
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// register custom intent filter
*registerReceiver(new AlarmNotificationReceiver(),new IntentFilter(Intent.ACTION_BATTERY_CHANGED));*
\[enter image description here\]\[1\]
show = (Button)findViewById(R.id.btn_show);
show.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
startAlarm(true,true);
}
});
myWebView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://google.com");
myWebView.setWebViewClient(new WebViewClient());
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void startAlarm(boolean isNotification, boolean isRepeat) {
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent myIntent;
PendingIntent pendingIntent;
// SET TIME HERE
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,45);
myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
if(!isRepeat)
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
else
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
}][1]

1)But the above code may not work in all versions i.e notofication will not came oreo(8.0) and above.beacause of NotificationBuilder is depricated and background execution limits.Go to
2)Use Notification Channel .like below
use this code.hope its works fine!!!
void issueNotification()
{
// make the channel. The method has been discussed before.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
makeNotificationChannel("CHANNEL_1", "Example channel", NotificationManager.IMPORTANCE_DEFAULT);
}
// the check ensures that the channel will only be made
// if the device is running Android 8+
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this, "CHANNEL_1");
// the second parameter is the channel id.
// it should be the same as passed to the makeNotificationChannel() method
notification
.setSmallIcon(R.mipmap.ic_launcher) // can use any other icon
.setContentTitle("Notification!")
.setContentText("This is an Oreo notification!")
.setNumber(3); // this shows a number in the notification dots
NotificationManager notificationManager =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1, notification.build());
// it is better to not use 0 as notification id, so used 1.
}

Related

How to trigger a launch Activity intent when my app is closed on Android 10/Q?

I am trying to create an app that will open another app at a specified time. To do this, I used an AlarmManager that starts a service. It works just fine if my app is open when the alarm is triggered. I get a notification that the service started, and the other app opens. However, if my app is in the background (after pressing the home button), and the alarm triggers, I get a notification that the service started, but the other app does not launch. What am I doing wrong? I am testing this on a Pixel 3 emulator running API level 29 (Android 10/Q).
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE=101;
public static int aHour;
public static int aMinute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setAlarm() {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, amReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, aHour);
calendar.set(Calendar.MINUTE, aMinute);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
//Some code that sets aHour and aMinute
//Some code that triggers setAlarm()
}
amReciever.java
public class amReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, launcherService.class);
ContextCompat.startForegroundService(getApplicationContext(), i);
}
}
launcherService.java
public class launcherService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("App is launching.")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
Intent launcher = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.example.app");
if (launcher != null) {
startActivity(launcher);
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<service android:name=".launcherService"
android:enabled="true"
android:exported="true" />
As of Android 10 (API level 29), you cannot start activities from the background anymore.
There are a number of exceptions to this rule that may or may not apply to your given scenario.
If none of the exceptions apply, you might want to consider displaying a high-priority notification, possibly with a full-screen Intent.

How to send data from a class to an Activity in Android

I am implementing FCM(Firebase cloud messaging) for push notifications. I could get push notification from the server using my service class successfully. But, how do I send data(messages) from the service class to the activity?
Service.java
public class Service extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, FCMActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.RED, 1000, 300);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
FCMActivity.java
public class FCMActivity extends AppCompatActivity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fcm);
mTextView = (TextView) findViewById(R.id.txt);
}
}
There are several options, among those are:
Register a BroadcastReceiver inside your Activity with an IntentFilter for your custom action (action is just a String identifier for a broadcast message type), and send the broadcast from service using LocalBroadcastManager.getInstance().sendBroadcast(Intent intent) method
Use an event bus, for example the very popular GreenRobot EventBus library. See https://github.com/greenrobot/EventBus#eventbus-in-3-steps for explanation.
Both of these options require registering and unregistering a listener / receiver inside your Activity, which is best done in onResume/onPause for events that should trigger UI changes.
Additionally, you can bind to the service from your Activity.
You should use IBinder in your service and ServiceConnection in your Activity

Error with Notification.Builder in notify

Hello I am new to Android, and I 'm trying to create notifications Notification.Builder and I failed . When launching the notification I get error
nm.notify(IDNOTIFICACIONUNO,notif); // Error in notif
I have downloaded the API 'S 16 17 18 19 23,
and this is all code :
public class MainActivity extends AppCompatActivity {
NotificationManager nm;
private static final int IDNOTIFICACIONUNO = 1;
Notification notif;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLanzar = (Button) findViewById(R.id.boton_notificacion);
btnLanzar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),segundaVentana.class);
PendingIntent intencionPendiente = PendingIntent.getActivity(getApplicationContext(),0,i,0);
Notification.Builder notif = new Notification.Builder(getApplicationContext());
notif.setSmallIcon(R.drawable.tree);
notif.setTicker("App Nature ¡TIP!");
notif.setWhen(System.currentTimeMillis());
notif.setContentTitle("App Nature ¡TIP!");
notif.setContentText("Cierra la llave, cuando te estes cepillando");
notif.setContentInfo("TIP");
notif.setContentIntent(intencionPendiente);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(IDNOTIFICACIONUNO,notif);
}
});
}
I also libraries . Thank you for your help
there is a ` characheter after notif.setSmallIcon(R.drawable.tree);
remove that charachter and code will run.
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Connect to the button
Button iconBtn = (Button) findViewById(R.id.btn_icon);
//Set the button on click listener
iconBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notification = builder.setContentIntent(contentIntent).setTicker("This is a notification marquee")
.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle("Message Title")
.setContentText("Message Content").build();
//Show the notification
nm.notify(1, notification);
}
});

press a button and show notification

i have a button in xml when it is clicked following code should show a notification bit its not running giving an error ( Notification.Builder(new View.OnClickListener(){}) is undefined)
anybody tell whats the problem
Mainactivity.Java
package com.example.auto;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b =(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,
0, intent, 0);
Notification mNotification = new Notification.Builder(this)
.setContentTitle("New Post!")
.setContentText("Here's an awesome update for you!")
.setContentIntent(pIntent)
.addAction(0, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotification);
}
});
}
}
Try this one :)
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(getApplicationContext(), MYDEMOACTIVITY.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(MYDEMOACTIVITY.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.
mNotificationManager.notify(mId, mBuilder.build());
The constructor needs a Context, and the OnClickListener is no Context.
Change this:
Notification mNotification = new Notification.Builder(this)
to:
Notification mNotification = new Notification.Builder(MainActivity.this)
Notification mNotification = new Notification.Builder(this)
You can't use 'this' as the context because with it you are referencing your new OnClickListener, not your Activity.
To get the enclosing Activity's context you have to use MainActivity.this:
Notification mNotification = new Notification.Builder(MainActivity.this)

How to clear notification on notification action click?

I'm developing an android app where I display notifications with actions. But on action click notification not clearing, It stuck in that shade. How do I clear a notification on action click?
MY CODE
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
PendingIntent openSettingsActivity = PendingIntent.getActivity(this,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.addAction(R.drawable.ic_notification_button, "Settings", openSettingsActivity);
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setColor(color);
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
notificationBuilder.setContentIntent(openSettingsActivity);
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());
Hiding notifications should be processed in the place where the intent is sent.
In your current code:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("hide_notification", true); //add boolean to check later in activity if it should remove notification on activity create
And in your activity smth like this, to check if it should remove notification:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check for notification remove
boolean hideNotification = getIntent().getBooleanExtra("hide_notification", false);
if (hideNotification) {
NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
nmc.cancel(1); //1 - is your notification id
}
}
Depends on what you want, maybe it will be better to call that not in onCreate() but onStart()

Categories

Resources