How to start activity when user clicks a notification? - java

I am attempting to convert some code I found in a tutorial for my own use. Originally, the code launched the system contacts list when the user would click a notification generated by my app. I am trying to start an Activity of my own instead of launching the contact list, but it's not working. More specifically, nothing happens. There is no error, and my Activity doesn't load either. The notification window disappears after clicking, and the original Activity is still visible.
Here is my code:
public class MyBroadcastReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
public void onReceive(Context context, Intent intent){
Bundle extras = intent.getExtras();
String deal = (String) extras.get("Deal");
String title = "Deal found at " + (String) extras.get("LocationName");
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notifyDetails = new Notification(R.drawable.icon, title,System.currentTimeMillis());
Class ourClass;
try {
ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
Intent startMyActivity = new Intent(context, ourClass);
PendingIntent myIntent = PendingIntent.getActivity(context, 0,startMyActivity, 0);
notifyDetails.setLatestEventInfo(context, title, deal, myIntent);
notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
notifyDetails.flags |= Notification.DEFAULT_SOUND;
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
This is my entry in the AndroidManifext.xml file...
<activity android:name=".ViewTarget" android:label="#string/app_name" >
<intent-filter>
<action android:name="com.kjdv.gpsVegas.ViewTarget" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And this is my Activity that I want to launch...
public class ViewTarget extends ListActivity {
public ListAdapter getListAdapter() {
return super.getListAdapter();
}
public ListView getListView() {
return super.getListView();
}
public void setListAdapter(ListAdapter adapter) {
super.setListAdapter(adapter);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locations);
Log.v("db", "Inside ViewTarget");
}
}

Which Android version are you running on? You might wanna try using NotificationCompat instead. This class is include in the latest support package.
Intent notificationIntent = new Intent(context, ViewTarget.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = context.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.app_icon)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.app_icon))
.setTicker(payload)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("Message")
.setContentText(payload);
Notification n = builder.getNotification();
n.defaults |= Notification.DEFAULT_ALL;
nm.notify(0, n);
EDIT:
I know this is an old thread/question but this answer helped me for showing the activity when tapping the notification.
For those people that this isn't working is probably because you haven't "registered" the activity in your manifest. For example:
<activity
android:name="com.package.name.NameOfActivityToLaunch"
android:label="Title of Activity" >
<intent-filter>
<action android:name="com.package.name.NAMEOFACTIVITYTOLAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And, hopefully, this should work.
Hope it helped...

you should set action and category for Intent.
Intent startMyActivity = new Intent(context, ourClass);
startMyActivity .setAction(Intent.ACTION_MAIN);
startMyActivity .addCategory(Intent.CATEGORY_LAUNCHER);
it works

I figured out the problem. I forgot to include the package name in the activity declaration in the Manifest file.
Wrong:
activity android:name=".ViewTarget" android:label="#string/app_name"
Correct:
activity android:name="com.kjdv.gpsVegas.ViewTarget" android:label="#string/app_name"

Can you try removing the Intent filter, so it looks like this:
<activity android:name=".ViewTarget" android:label="#string/app_name" />
Also, not sure if this code will work:
ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
Intent startMyActivity = new Intent(context, ourClass);
Can you try it like this instead:
Intent startMyActivity = new Intent(context, ViewTarget.class);

In order to launch an Activity from an Intent, you need to add a flag:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is true even if you declare the class in the Intent's constructor.

check this code
public class TestActivity extends Activity {
private static final int UNIQUE_ID = 882;
public static NotificationManager nm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent navigationIntent = new Intent();
navigationIntent.setClass(classname.this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
0);
String body = "New notificattion added!!!";
String title = "Notification";
Notification n = new Notification(R.drawable.icon, body,
System.currentTimeMillis());
//this is for giving number on the notification icon
n.number = Integer.parseInt(responseText);
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(UNIQUE_ID, n);

Related

The notification is displayed, but clicking the notification cannot jump to the page

Goal: click the button to jump out of the notification, the user can jump from the notification to another page.
The notification is displayed but clicking the notification cannot jump to the page.
I think the PendingIntent is wrong.
How to fix it?
public class MainActivity extends AppCompatActivity {
private String CHANNEL_ID = "Coder";
NotificationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "DemoCode", NotificationManager.IMPORTANCE_DEFAULT);
manager = getSystemService(NotificationManager.class);
assert manager != null;
manager.createNotificationChannel(channel);
}
Button btDefault,btCustom;
btDefault = findViewById(R.id.button_DefaultNotification);
btCustom = findViewById(R.id.button_CustomNotification);
btDefault.setOnClickListener(onDefaultClick);
}
private final View.OnClickListener onDefaultClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextIntent = new Intent(MainActivity.this, secondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, nextIntent,PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
builder.setContentTitle("Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.ic_baseline_accessible_forward_24);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
manager.notify(1, builder.build());
}
Check if this works for you. As mentioned in android api
You should consider user's expected navigation experience. So for making the best navigation using pendingIntent with Notification, you should do as follow:
1. First define your app's hierarchy inside AndroidManifest.xml:
<activity
android:name=".MainActivity"
... >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity is the parent for SecondActivity -->
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity" />
...
</activity>
Now you told android that when a notification clicked, SecondActivity would be the child of MainActivity when user is navigating up.
2. Create PendingIntent using TaskStackBuilder:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pendingIntent = TaskStackBuilder.create(MainActivity.this)
.addNextIntentWithParentStack(intent)
.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
Then you can set the PendingIntent we created to the notification. And now if user touches the notification, android system will navigate him to SecondActivity while holding MainActivity in back stack.

Android BroadcastReceiver not working by clicking at notification action

I'm building a music player app and I have a problem with the notification part I think all of my code about the notification is right but when I tap at notification controller buttons broadcast receiver don't work.
AndroidManifest:
<receiver android:name=".notification.NotificationController">
<intent-filter>
<action android:name="com.ydp.eight_d_musicplayer.ACTION_NOTIFY_PLAY_PAUSE"/>
<action android:name="com.ydp.eight_d_musicplayer.ACTION_NOTIFY_SKIP_NEXT"/>
<action android:name="com.ydp.eight_d_musicplayer.ACTION_NOTIFY_SKIP_PREVIOUS"/>
</intent-filter>
</receiver>
My Broadcast:
public class NotificationController extends BroadcastReceiver {
public static String ACTION_NOTIFY_PLAY_PAUSE = "com.ydp.eight_d_musicplayer.ACTION_NOTIFY_PLAY_PAUSE";
public static String ACTION_NOTIFY_SKIP_NEXT = "com.ydp.eight_d_musicplayer.ACTION_NOTIFY_SKIP_NEXT";
public static String ACTION_NOTIFY_SKIP_PREVIOUS = "com.ydp.eight_d_musicplayer.ACTION_NOTIFY_SKIP_PREVIOUS";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_NOTIFY_PLAY_PAUSE)){
if (Player.player.isPlaying()){
Player.player.pause();
}else {
Player.player.start();
}
} else if (intent.getAction().equals(ACTION_NOTIFY_SKIP_PREVIOUS)){
Toast.makeText(context, "previous", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "next", Toast.LENGTH_SHORT).show();
}
}
}
And My Service:
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,new Intent(this, MainActivity.class),0);
Intent previous = new Intent();
previous.setAction(ACTION_NOTIFY_SKIP_PREVIOUS);
Intent play = new Intent();
play.setAction(ACTION_NOTIFY_PLAY_PAUSE);
Intent next = new Intent();
play.setAction(ACTION_NOTIFY_SKIP_NEXT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notification = new Notification.Builder(this, "playback")
.setSmallIcon(R.drawable.music_icon)
.setContentTitle(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE))
.setContentText(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM) + " . " + retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST))
.setLargeIcon(songCover)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.addAction(R.drawable.ic_skip_previous_black_24dp,"previous",PendingIntent.getBroadcast(this,11,previous,PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(R.drawable.ic_pause_black_24dp,"play",PendingIntent.getBroadcast(this,12,play,PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(R.drawable.ic_skip_next_black_24dp,"next",PendingIntent.getBroadcast(this,13,next,PendingIntent.FLAG_UPDATE_CURRENT))
.setContentIntent(pendingIntent);
Notification.MediaStyle mediaStyle = new Notification.MediaStyle();
mediaStyle.setBuilder(notification);
startForeground(1, mediaStyle.build());
}
Help, please!
Initialize the Intents like this:
new Intent(this, NameOfTheClass.class);
In cases where you are in coroutine for example use
applicationContext

Notification not showing up when I close the app

So I made some code that makes the app show up at the time specified. It works well enough when the app is open on the screen, but when it is closed, it doesn't work at all. I need help making it show up.
Code for MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initChannels(this);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 00);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
Code for MyReceiver.java which extends BroadcastReceiver:
public MyReceiver() {
}
#Override
public void onReceive(Context context,Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
Code for MyNewIntentService which extends IntentService:
private static final int notificationId = 4242;
public MyNewIntentService() {
super("MyNewIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
//NOTIFICATION CREATION
// Create an explicit intent for an Activity in your app
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("This is the title")
.setContentText("This is the body of the notification.")
.setVisibility(VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());
}
And I added this in the AndroidManifest.xml:
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false" >
</receiver>
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>
I know there's a lot of text in this question and I apologize for that, but I think that'll make it easier for you to help me or see what the problem is.
try this
firebase notification are two types:
data message: when your app background/foreground/killed your push notification is worked
display message: when your app foreground push notification works
Handle push notification these stages background/foreground/killed
it depends your json response make sure your json response like this:
{
"to": "registration_ids",
"data": {
"key": "value",
"key": "value",
"key": "value",
"key": "value"
}
}
this is my code when your app background/foreground/killed it works fine
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "remoteMessage......" + remoteMessage.getData());
try {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e(TAG, object.toString());
body = object.getString("not_id");
dataa = object.getString("data");
title = object.getString("not_type");
type = object.getString("type");
Sender = object.getString("Sender");
SenderProfileUrl = object.getString("SenderProfileUrl");
wakeUpScreen();
addNotification(remoteMessage.getData());
}
/* when your phone is locked screen wakeup method*/
private void wakeUpScreen() {
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
Log.e("screen on......", "" + isScreenOn);
if (isScreenOn == false) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
}
/*Add notification method use for add icon and title*/
private void addNotification(Map<String, String> data) {
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?R.drawable.logo_app: R.drawable.logo_app;
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(icon)
//.setSmallIcon(R.drawable.logout_icon)
.setContentTitle(data.get("title") + "")
.setChannelId("channel-01")
.setAutoCancel(true)
.setSound(uri)
.setContentText(data.get("body") + "");
Notification notification = new Notification();
Log.e(TAG, "titlee" + data.get("title"));
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (sound)
notification.defaults |= Notification.DEFAULT_SOUND;
if (vibration)
notification.defaults |= Notification.DEFAULT_VIBRATE;
builder.setDefaults(notification.defaults);
}
}
when i click notification bar goto the particular screen using type like this:
/*notification send with type calling */
if (data.get("not_type").equals("calling")) {
if (data.get("type").equals("name")) {
Log.e(TAG, "ttt--" + type);
Intent notificationIntent = new Intent(this, CallingActivity.class);
notificationIntent.putExtra("notification_room_id", body);
notificationIntent.putExtra("data", dataa);
notificationIntent.putExtra("calling", "calling");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setSound(uri);
builder.setAutoCancel(true);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel("channel-01", name, importance);
manager.createNotificationChannel(mChannel);
}
manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), builder.build());
}
this is my manifest add notification class and token class
<service android:name=".notification.NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".notification.TokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".notification.NLService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
i hope it helps you

Notification using Firebase and Android

I am trying to make an android application where I receive notification using firebase. I followed resources available over the internet.
All I want to do is send notification from firebase, the message that I receive I want to display it in TextView in main activity.
Currently I am testing in an emulator. There are few problems that I am not able to resolve.
I am able to send notification from firebase but:
When the application is running in foreground I don't receive a notification in the android notification panel and nothing happens in the main activity too. That is the text in TextView does not change.
When the application is running in background I do receive the notification in android notification panel with message sent from firebase, clicking the notification main activity opens but the text in TextView does not change.
Firebase Messaging Service
public class VAFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "VAFirebaseMessagingS";
public VAFirebaseMessagingService() {}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("text"));
}
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
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);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private TextView userFeedbackQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFeedbackQuery = (TextView) findViewById(R.id.pfiva_user_feedback_query);
final Intent intent = getIntent();
if(intent.hasExtra(Intent.EXTRA_TEXT)) {
String userFeedbackQueryText = intent.getStringExtra(Intent.EXTRA_TEXT);
userFeedbackQuery.setText(userFeedbackQueryText);
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.pfiva.mobile.voiceassistant">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".messaging.FirebaseInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".messaging.VAFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
Please can someone guide what is wrong here? How can i solve the above two problems.
Thanks
After suggestions i made the below changes in Messaging Service, basically added notification channel.
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
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, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
Problem i face now is that when the app is running in background, i do receive notification in notification panel and clicking on it open main activity but the text in TextView is not updated.
Two ideas to solve your issue:
Have you register your VAFirebaseMessagingService in your AndroidManifest.xml:
Since Android 8, you must use an Notification Channel to send push notifications. Android

Notification.Builder does not create a notification

Im trying to create a notification from an edittext and broadcast receiver. In my first Activity the user should input a message and push the broadcast button. I want to take that string and create a notification from it and open a new activity that displays the message. I am doing all the notification work in my broadcast receiver class.
I have looked around onlne at examples and other peoples code but im not sure what im not getting right. The application loads up just fine and the broadcast button sends the broadcast to the receiver and Logs the string but the notification is never created.
Thanks for any help.
Broadcast class that sends broadcast message:
public class BroadcastReceiverActivity extends Activity
{
EditText et;
Button btn1;
public static String BString = "HappyHemingway";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_receiver);
et = (EditText)findViewById(R.id.et1);
btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message = et.getText().toString();
send(message);
}
});
}
/*
* This function creates an intent and
* sends a broadcast from the message
* parameter passed in.
*/
protected void send(String msg)
{
Log.i("msg", msg);
Intent i = new Intent();
i.putExtra("message",msg);
i.setAction(BString);
sendBroadcast(i);
}
}
Receiver class that creates notification:
public class Receiver extends BroadcastReceiver
{
// #SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action!=null&&action.equals("HappyHemingway"))
{
String msg = intent.getStringExtra("message");
Log.i("Received",msg);
Intent i = new Intent(context,ViewNotification.class);
i.putExtra("message",msg);
PendingIntent pi = PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context).
setSmallIcon(0).setAutoCancel(true).setTicker(msg).
setWhen(System.currentTimeMillis()).setContentTitle("New Notification!").
setContentText(msg).setContentIntent(pi);
NotificationManager mgr = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = builder.build();
mgr.notify(0, n);
Log.i("Received again",msg);
}
}
}
notification viewer class that is never launched
public class ViewNotification extends Activity
{
String text;
TextView txttext;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.viewnotification);
NotificationManager notificationmanager;
notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationmanager.cancel(0);
Intent i = getIntent();
text = i.getStringExtra("message");
txttext = (TextView) findViewById(R.id.text);
txttext.setText(text);
Log.i("made it", "made it made it made it");
}
}
manifest
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".BroadcastReceiverActivity"
android:label="#string/app_name" >
<action android:name="android.intent" />
<category android:name="android.intent.category.LAUNCHER" />
</activity>
<activity android:name=".ViewNotification"></activity>
<receiver android:name="Receiver">
<intent-filter>
<action android:name="HappyHemingway">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Hopefully its just a simple error I'm overlooking.This is my first time using Android Studio instead of Eclipse but I dont see how that could make any difference under than my unfamiliarity with the IDE.
Anything helps
thanks.
I'm not sure why I had setSmallIcon(0.)
When I changed it to setSmallIcon(R.drawable.ic_launcher) everything worked fine.

Categories

Resources