I have two activities, one called SplashActivity which is the Launcher and the main activity of the app and the second called MainActivity which is the child activity of SplashActivity, based on some event i have a notification created and when notification click i want the MainActivity to open and send data in extra.
My problem is i have tried every solution pops in front of me nothing worked.
this is my current code:
NotificationChannel channel = new NotificationChannel(String.valueOf(12), name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
notificationManagerCompat.createNotificationChannel(channel);
// Create an Intent for the activity you want to start
Intent notifyIntent = new Intent(getApplicationContext(), SplashActivity.class);
notifyIntent.putExtra("notify", "notify");
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Create the PendingIntent
PendingIntent notifyPendingIntent = PendingIntent.getActivity(
this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, String.valueOf(12))
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(body)
.setVibrate(new long[]{0, 100, 1000, 300})
.setAutoCancel(true)
.setContentIntent(notifyPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// notificationId is a unique int for each notification that you must define
notificationManagerCompat.notify(12, notification);
two activities declaration in manifest:
<activity
android:name=".home.activities.MainActivity"
android:parentActivityName=".SplashActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".SplashActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
any one what is the solution? and why my current code is not working?
please help me i been working two days for this to work.
You forgot putExtra to intent when start MainActivity, you only show log. Try this
Intent i = new Intent(this, destinationActivity);
i.putExtras(getIntent());
Log.e(TAG, "navigateTo: " + getIntent().getStringExtra("notify"));
startActivity(i);
finish();
after a while trying different solutions i didn't know what the problem is.
but what i did is i used this code:
if (getIntent().getExtras() != null)
getIntent().getExtras().keySet().iterator().forEachRemaining(new Consumer<String>() {
#Override
public void accept(String s) {
Log.e(TAG, "accept: " + s);
}
});
to print out the extras keys i have when the activity opens from notification i saw a unique set of keys and i used one of them as trigger for specific action when it opens from notification.
Related
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.
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
I was developing an app that receives Firebase push notification from my server. However this issue happens inconsistently, I may receive the notification and stay displaying it or sometimes disappears from Lock Screen and Top Notification Bar after a few seconds.
Below is my display notification after Firebase onMessageReceived code:
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Resources res = this.getResources();
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_timer_icon)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_timer_icon))
.setContentTitle("Firebase Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setOngoing(true)
.setPriority(1)
.setSound(defaultSoundUri)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent);
Notification noti = notification.build();
noti.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_SHOW_LIGHTS;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
AndroidManifest.xml:
<service android:name=".FirebaseNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
All I want is the notification stay displaying like Whatsapp messages appear on lockscreen and top notification bar which only disappear when user click on it. Any solution?
***I also called a service which will run AsyncTask in another class to call a web service right after my app display the notification. So far, this has run successfully when app is in foreground and background. Do you think this might affect the notification?
Here's my problem:
I have an application which includes 3 activities.
-SplashscreenActivity (Launcher - Main)
-LoginActivity
-HomeActivity
--Application killed:--
Normal process:
when I run the application by the dashboard icon, I go through the splash, (i logged in), and coming up on the home.
If I put the application in background and I raise it by the dashboard icon, I go back on the home. Everything is normal.
--Application killed:--
However, for the following process:
I get a push notification. I run the application by this push, I go through the splash, and coming up on the home.
But if I put the application in the background, and I raise it by the dashboard icon, I go through by the splash again systematically. Here is the problem!
Here's my manifest.xml ( EDITED )
<activity
android:name="my.package.SplashscreenActivity"
android:label="#string/app_name"
android:noHistory="false"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="my.package.LoginActivity"
android:label="#string/app_name"
android:noHistory="false"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
<activity
android:name="my.package.HomeActivity"
android:label="#string/app_name"
android:noHistory="false"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
Here's my push notifications BroadcastReceiver (sendNotificationMethod)
private void sendNotification(String message, String title, int count, String type, long threadId)
{
Activity m_activity;
if (App.getInstance().m_currentActivity != null && App.getInstance().isOnPause())
m_activity = App.getInstance().m_currentActivity;
else
m_activity = null;
PendingIntent pendingIntent = null;
Intent intent = null;
if (m_activity != null)
{
intent = new Intent(this, m_activity.getClass());
intent.putExtra("type", type);
intent.setData((Uri.parse("foobar://" + SystemClock.elapsedRealtime())));
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
}
else
{
PackageManager pm = getPackageManager();
intent = pm.getLaunchIntentForPackage("my.package");
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("type", type);
pendingIntent = PendingIntent.getActivity(App.getInstance(), 0, intent, 0);
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo_push_lolilol)
.setColor(App.getInstance().getResources().getColor(R.color.colorPrimary))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)threadId, notificationBuilder.build());
}
Do you have "the solution"?
Thank you in advance.
Try this
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
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);