Error with Notification.Builder in notify - java

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

Related

How to Return to activity after the notification has appeared? Notification is not clickable

I have problem - it is not possible to return to the main activity after clicking on the received notification. The notification itself is not clickable. The notification is triggered in the onPause method (in the background)
My main activity is MainActivity, which is setting up notification via PendingIntent and AlarmManager
public class MainActivity extends AppCompatActivity {
private NotificationManager notificationManager;
private static final int NOTIFY_ID = 1;
private static final String CHANNEL_ID = "CHANNEL_ID";
NotificationPublisher notificationPublisher;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
CharSequence name = "LemubitReminderChannel";
String description = "Channel for Lemubit Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyLemubid", name, importance);
channel.setDescription(description);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
private void reminderMethod (){
Toast.makeText(this, "Напоминание о запуске фонового уведомления", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), NotificationPublisher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
long inPauseTime = System.currentTimeMillis();
long ten = 2 * 1000;
alarmManager.set(AlarmManager.RTC_WAKEUP, inPauseTime + ten, pendingIntent);
}
#Override
protected void onPause() {
super.onPause();
reminderMethod();
}
}
Broadcast receiver
public class NotificationPublisher extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
int unicode = 0x1F62D;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "notifyLemubid")
.setAutoCancel(true)
.setContentTitle("текст " + getEmojiByUnicode(unicode))
.setContentText("текст")
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(200, builder.build());
}
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}
}
You need to set the contentIntent on the Notification, then, when the user clicks the Notification, the contentIntent will be dispatched. If you want the user to open an Activity of your app, then just create an Intent to your Activity, wrap that in a PendingIntent and call setContentIntent() on the `Notification. There's hundreds of howtos and tutorials for how to do this, just search a bit.

Need some help troubleshooting code that schedules daily notifications

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.
}

How to back to Main activity from the notification activity?

When I press the notification the activity opens, but when I click back the App go to background and still on the same activity.
I wanna go back to MainActivity when I click back. what's wrong in my code?
public class MainActivity extends AppCompatActivity {
NotificationManagerCompat notificationManager;
NotificationCompat.Builder n;
String ID = "a" ;
int id=1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b2(View view) {
Intent i = new Intent(MainActivity.this, Main2.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(i);
PendingIntent pi = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
n = new NotificationCompat.Builder(this, ID)
.setSmallIcon(R.drawable.xx)
.setContentTitle("don't forget")
.setContentText("Hello0o0o0o")
.setContentIntent(pi)
.setAutoCancel(true);
notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id , n.build());
id++;
}
public void b1(View view) {
Intent i4 = new Intent(this,Read.class);
startActivity(i4);
}
}
From your code I don't see the problem, but you could override the onBackPressed() function to move back to MainActivity. It's a solution. Also check if you actually are calling this function b2.

ImageButton isnt working on Custom Notification - Android

I'm trying to create a custom notification with ImageButton.
When onclicked, the ImageButton should start an activity named TaskActivity, but i'm unable to achieve this.
The followings are my codes:
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
//button intents
Intent cmdIntent = new Intent(
MainActivity.this, cmdButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, cmdIntent, 0);
//notification mgr
int notifyID = 001;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotifyMgr = (NotificationManager)getSystemService(ns);
//new notification
int icon = R.drawable.icon3;
long when = System.currentTimeMillis();
#SuppressWarnings({ "deprecation" })
Notification notify = new Notification(icon,getString(R.string.text),when);
//remote views
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.custom_notification);
contentView.setImageViewResource(R.id.notification_image, R.drawable.icon4);
contentView.setTextViewText(R.id.notification_title, "APP TITLE");
contentView.setTextViewText(R.id.notification_text, "hello");
contentView.setOnClickPendingIntent(R.id.notification_image, pendingSwitchIntent);
notify.contentView = contentView; //set
//notification intent
Intent nIntent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nIntent, 0);
notify.contentIntent = contentIntent;
mNotifyMgr.notify(notifyID,notify);
}
public class cmdButtonListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent){
System.out.println("Here, I am here");
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
}
}
Android Manifest
<receiver android:name=".MainActivity$cmdButtonListener" />
I dont know, where i'm wrong as i'm doing exactly as it is shown in most of the tutorials online. :(
Finally I've found a solution...
Declare the below variable
private static Context mContext;
Add below code inside public void onCreate(Bundle savedInstanceState) {
mContext = this;
Finally, change the below piece of code in public class cmdButtonListener extends BroadcastReceiver{
Intent newAct = new Intent(MainActivity.this, TaskActivity.class);
startActivity(newAct);
To
Intent Act = new Intent(mContext,TaskActivity.class);
mContext.startActivity(Act);

Get EditText value displayed AlertDialog

Is it possible to get the user-input text from an EditText and display it in an AlertDialog? The Main Activity prompts the user to set an alarm, then enter a message to be displayed later once the alarm goes off. I want to be able to display whatever message the user typed in an AlertDialog.
MainActivity.java
public class MainActivity extends Activity{
TimePicker picker;
DatePicker datepicker;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings, menu);
return true;
}
public void setAlarm(View view) {
picker = (TimePicker)findViewById(R.id.timePicker1);
datepicker = (DatePicker)findViewById(R.id.datePicker1);
Calendar AlarmCal = Calendar.getInstance();
Intent intent = new Intent(this, AlarmBoadcastReceiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(this.getApplicationContext(), 9988, intent, 0);
AlarmCal.setTimeInMillis(System.currentTimeMillis());
AlarmCal.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
AlarmCal.set(Calendar.MINUTE, picker.getCurrentMinute());
AlarmCal.set(Calendar.DATE, datepicker.getDayOfMonth());
AlarmCal.set(Calendar.YEAR, datepicker.getYear());
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, AlarmCal.getTimeInMillis(), pendingintent);
}
}
AlarmBroadCastReciever.java
public class AlarmBoadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
}
private void showNotification(Context context) {
PendingIntent contentintent = PendingIntent.getActivity(context, 0, new Intent(context, ShowDialog.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle("Reminder")
.setContentText("Click Here To View Message");
mBuilder.setContentIntent(contentintent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
ShowDialog.java
public class ShowDialog extends Activity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_dialog);
showDialog();
}
void showDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Message");
alertDialogBuilder
.setMessage("message")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ShowDialog.this.finish();
closeApp();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
So when the notification is clicked on, the AlertDialog shows up, but not with the message the user entered. Ive tried getting the values and putting them in a string, but that doesnt work. Any Ideas?
Try to create your own Dialog extending from Dialog class and add this message to constructor.
I hate to answer my own question but I took the advice #StarsSky gave and used Shared Preferences to store and retrieve the message to display in the AlertDialog
save
SharedPreferences.Editor editor = getSharedPreferences(null, MODE_PRIVATE).edit();
editor.putString("text", editText.getText().toString());
editor.commit();
receive
SharedPreferences prefs =getSharedPreferences(null, MODE_PRIVATE);
String text = prefs.getString("text", null);
Add the message as an EXTRA to the alarm pendingIntent:
Intent intent = new Intent(this, AlarmBoadcastReceiver.class);
intent.putExtra("message", yourMessageString);
Get the string in AlarmBoadcastReceiver onReceive method
yourMessageString = intent.getExtras().getString("message","No message");
In showNotification add that string as an EXTRA to pendingintent:
intent = new Intent(context, ShowDialog.class);
intent.putExtra("message", yourMessageString);
PendingIntent contentintent = PendingIntent.getActivity(context, 0, intent, 0);
On ShowDialog onCreate method get the intent extra:
userMessage = getIntent().getExtras().getString("message","No message");
Then set that message to AlertDialog
alertDialogBuilder.setMessage(userMessage)

Categories

Resources