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);
Related
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.
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.
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);
}
});
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)
I would like to put two buttons on my notifications from the status bar. Of course they do not appear until the user touches to expand them. I have created the custom layout for my notification using RemoteViews but am unsure if it's possible to obtain a reference to them because of my current code structure.
#Override
public void onMessage(Context context, Intent intent) {
Log.w("C2DMReceiver",
"Message Received, this is the message with no payload");
Bundle extras = intent.getExtras();
if (extras != null) {
String[] payload = new String[3];
payload[0] = (String) extras.get("payload");
payload[1] = (String) extras.get("payload2");
SharedPreferences sharedP = Prefs.get(this);
boolean inApp = sharedP.getBoolean("currentlyInApp", true);
if (!inApp) {
createNotification(context, payload);
}
}
}
public void createNotification(Context context, String[] payload) {
SharedPreferences sharedP = Prefs.get(context);
boolean needsToLogin = sharedP
.getBoolean("loginFromNotification", true);
Log.w("C2DMReceiver", "createNotification called");
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, WebViewActivity.class);
Intent notificationIntent2 = new Intent(this, UniteActivity.class);
PendingIntent pIntent;
if (needsToLogin) {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent2,
PendingIntent.FLAG_CANCEL_CURRENT);
} else {
pIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
// Compatibility builder
NotificationCompat.Builder notification = new NotificationCompat.Builder(
context);
RemoteViews remote = new RemoteViews(getPackageName(),R.layout.notification);
//Button okButton = (Button) findViewById(R.layout.notification);
notification.setAutoCancel(false);
notification.setContent(remote);
notification.setContentIntent(pIntent);
notification.setWhen(System.currentTimeMillis());
notification.setTicker(payload[0]);
notification.setSmallIcon(R.drawable.default1);
notification.setContentTitle(payload[1]);
notification.setContentText(payload[0]);
long duration[] = { 100, 300, 100 };
notification.setVibrate(duration);
notificationmanager.notify(0, notification.getNotification());
}
onMessage is a method pulled from the Google C2DM library where the notifications are generated by intents received from google. Without a view, how can I obtain a reference to my buttons using findViewById()? or some other means
I think you are looking for the method:
RemoteViews.setOnClickPendingIntent(int, android.app.PendingIntent)
So, if you add...
remote.setOnClickPendingIntent(R.id.button, pIntent);
...it should work.