I have problem that sometimes not received notification. In order to receive notification, I need to restart my application then execute notification.php and notification will appear.But after 30 minute/15 minute when i try again running notification.php , not received any notification (I need to run my app again). I hope you guys can help me solve this problem.Thank you in advance.
notification.php
<?php
require "../../init.php";
include("../../function_lib.php");
$id = $_GET['id'];
$title = "Try App";
$message = "news..";
$path_to_fcm = "https://fcm.googleapis.com/fcm/send"; //send push notification through this firebase url
$server_key = "####";
$topic = "/topics/reminder";
$type = "reminder";
//create http request to firease server
//request need 2 section : 1.header section 2. payload section
//add push notification in payload section
//header section for http request : that content authorization key and content_type of this application
//below are the header section of the http request
$headers = array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
/*
$field = array('to'=>$topic,'notification'=>array("title"=>"add title","text"=>"add text","click_action"=>"OPEN_ACTIVITY_1"),
'data'=>array('title'=>$title,'body'=>$message,'type'=>$type,'id'=>$id),'priority'=>"high");
*/
//echo "\n".$key;
// to = refer to fcm token, notification refer to message that wull be use in push notification.
///below are the payload section.
$field = array('to'=>$topic,
'data'=>array('title'=>$title,'body'=>$message,'type'=>$type,'id'=>$id));
//perform json encode
$payload = json_encode($field);
//pass $payload (content json encode) variable to firebase server
//below gonna start url section.gonna use firebase url http to send json to firebase server.
$curl_session = curl_init();
curl_setopt($curl_session,CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST,true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS, $payload);
//execute curl
$result = curl_exec($curl_session);
//close curl
curl_close($curl_session);
//close mysqli
//mysql_close($conn);
$path = "../dashboard.php?act=home";
echo ('<script>location.href="'.$path.'"</script>');
?>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mas.khoi.infoevent">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/icon_logo_only"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".firebase.FcmInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".firebase.FcmMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".ScreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".fragment.MainActivity">
</activity>
<activity android:name=".EventDetailsActivity">
</activity>
</application>
</manifest>
FcmInstanceIdService.java
public class FcmInstanceIdService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
//http://stackoverflow.com/questions/38340526/firebase-fcm-token-when-to-send-to-server
String recent_token = FirebaseInstanceId.getInstance().getToken();
//add token to sharepreference
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(Config.SETTING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Log.i("generate token",recent_token);
editor.putString(Config.SETTING_FCM_TOKEN,recent_token);
editor.commit();
}
}
FcmMessagingService.java
public class FcmMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//if want to use function below need to used change data to notification at $field at server side.
//String message = remoteMessage.getNotification().getBody();
//String title = remoteMessage.getNotification().getTitle();
if(remoteMessage.getData().size()>0){
Log.i("Notification Sucess",""+remoteMessage.getData());
startNotification(remoteMessage);
}else{
Log.i("Notification Failed",""+remoteMessage.getData());
}
}
public void startNotification(RemoteMessage remoteMessage){
String title = remoteMessage.getData().get("title");
String messsge = remoteMessage.getData().get("body");
String type = remoteMessage.getData().get("type");
String id = remoteMessage.getData().get("id");
Log.i("Notification","active");
//Log.i("Notificaition","type:"+type);
//Log.i("Notificaition","id:"+id);
//check if notification eihter is reminder or new quote/event
if (!type.equals("reminder") && id.equals("none")) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messsge);
notificationBuilder.setSmallIcon(R.drawable.icon_no_bg);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
//super.onMessageReceived(remoteMessage);
}else
if(type.equals("reminder") && ! id.equals("none")) {
Intent intent = new Intent(this, EventDetailsActivity.class);
intent.putExtra("id",id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messsge);
notificationBuilder.setSmallIcon(R.drawable.icon_logo_only);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
Please check this reference about when onMessageReceived() method is fired.
onMessageReceived() is fired only if app is in foreground for notification messages but for data messages, it will always get handled.
Related
I am building basic calling app using TelecomManager, ConnectionService and Connection. But, When an there is an incoming call, my incomingActivity UI is not showing up. Below is the sample code so far.
In my MainActivity.java
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivity(intent);
// ================================================================
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
// new ComponentName(getPackageName(), CallHandler.TAG), "myCallHandlerId");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
new ComponentName(getApplicationContext(), CallHandler.TAG), "myCallHandlerId");
PhoneAccount phoneAccount = PhoneAccount
.builder(phoneAccountHandle, "myCallHandlerId")
.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
.build();
manager.registerPhoneAccount(phoneAccount);
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle));
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).isEnabled());
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).getClass());
Log.i("Phone Account isEnabled", "" + phoneAccount.isEnabled());
Bundle bundle = new Bundle();
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, "555555555", null);
bundle.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri);
bundle.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
// manager.addNewIncomingCall(phoneAccountHandle, bundle);
Log.i("Permitted", "" + manager.isIncomingCallPermitted(phoneAccountHandle));
if(manager.isIncomingCallPermitted(phoneAccountHandle)){
Log.i("Call", "Incoming");
manager.addNewIncomingCall(phoneAccountHandle, bundle);
}
}
In my CallHandler.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallHandler extends ConnectionService{
public static final String TAG = CallHandler.class.getName();
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
#Override
public Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i("CallHandler","onCreateIncomingConnection");
// return super.onCreateIncomingConnection(connectionManagerPhoneAccount, request);
Context context = getApplicationContext();
Log.i("Context","" + context);
Log.i("Context","" + context.getPackageName());
Log.i("Context","" + getBaseContext());
Log.i("Context","" + context.getClass().getName());
Log.i("Context","" + context.getClass().getSimpleName());
CallConnection callConnection = new CallConnection(context);
callConnection.setInitializing();
callConnection.setActive();
callConnection.setCallerDisplayName("Manik", TelecomManager.PRESENTATION_ALLOWED);
// callConnection.setConnectionProperties(Connection.PROPERTY_SELF_MANAGED);
// callConnection.setConnectionCapabilities(Connection.CAPABILITY_HOLD & Connection.CAPABILITY_SUPPORT_HOLD);
return callConnection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
return super.onCreateOutgoingConnection(connectionManagerPhoneAccount, request);
}
}
In my CallConnection.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallConnection extends Connection {
private Context context;
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
public CallConnection(Context con) {
context = con;
setConnectionProperties(PROPERTY_SELF_MANAGED);
setAudioModeIsVoip(true);
}
#Override
public void onAnswer(int videoState) {
super.onAnswer(videoState);
Log.i("Call","Answered");
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onShowIncomingCallUi() {
Log.i("Call","Incoming Call");
super.onShowIncomingCallUi();
// MainActivity con = new MainActivity();
// Context context = con.getApplicationContext();
NotificationChannel channel = new NotificationChannel("channel", "Incoming Calls",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
// other channel setup stuff goes here.
// We'll use the default system ringtone for our incoming call notification channel. You can
// use your own audio resource here.
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
channel.setSound(ringtoneUri, new AudioAttributes.Builder()
// Setting the AudioAttributes is important as it identifies the purpose of your
// notification sound.
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
// NotificationManager mgr = context.getSystemService(NotificationManager.class);
// mgr.createNotificationChannel(channel);
// Create an intent which triggers your fullscreen incoming call user interface.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, IncomingCallScreenActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
Log.i("Intent1","" + intent);
Log.i("Intent2","" + intent.getPackage());
Log.i("Intent3","" + intent.getType());
Log.i("Intent4","" + intent.getData());
Log.i("Intent5","" + intent.getDataString());
Log.i("Intent6","" + intent.getAction());
Log.i("Intent7","" + intent.getCategories());
Log.i("Intent8","" + intent.getExtras());
Log.i("Pending Intent","" + pendingIntent);
Log.i("Pending Intent","" + pendingIntent.getCreatorPackage());
// Build the notification as an ongoing high priority item; this ensures it will show as
// a heads up notification which slides down over top of the current content.
final Notification.Builder builder = new Notification.Builder(context);
builder.setOngoing(true);
builder.setPriority(Notification.PRIORITY_HIGH);
// Set notification content intent to take user to fullscreen UI if user taps on the
// notification body.
builder.setContentIntent(pendingIntent);
// Set full screen intent to trigger display of the fullscreen UI when the notification
// manager deems it appropriate.
builder.setFullScreenIntent(pendingIntent, true);
// Setup notification content.
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Your notification title");
builder.setContentText("Your notification content.");
// Set notification as insistent to cause your ringtone to loop.
Notification notification = builder.build();
notification.flags |= Notification.FLAG_INSISTENT;
// Use builder.addAction(..) to add buttons to answer or reject the call.
NotificationManager notificationManager = context.getSystemService(
NotificationManager.class);
notificationManager.notify("Call Notification", 37, notification);
// context.startActivity(intent);
}
}
All the log messages inside onCreateIncomingConnection() and onShowIncomingCallUi() are showing up when the app launches, and not when there is an incoming call.
All the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<!--
Needed only if your calling app reads numbers from the `PHONE_STATE`
intent action.
-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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=".IncomingCallScreenActivity"></activity>
<activity android:name=".CallScreenActivity" />
<activity android:name=".ContactsActivity" />
<activity android:name=".LogsActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tel" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".CallHandler"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
Any help would be appreciated. Thanks
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
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'm trying to send a push notification to all devices from firebase but at first i tried only in my phone, it doesn't work, after that i tried in another phone and it doesn't work either. Finally with the 3rd one it work and it work at the second one magically. What i have to do to the push notifications work in all devices?
Manifest ->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.startingandroid.firebasecloudmessaging">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity" android:label="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" android:label="FCM"></activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application></manifest>
MyFirebaseInstanceIDService ->
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token in logcat
Log.e(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
} }
MyFirebaseMessagingService ->
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "StartingAndroid";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//It is optional
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
private void sendNotification(String title, String messageBody) {
Intent intent = new Intent(this, MainActivity.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(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
SplashActivity
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}, 4000);
}}
I have a broadcast receiver which detects oncoming notifications when the app is open and in background but when the recent app is cleared the receiver is not working please suggest me ideas.
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
JSONObject json = new JSONObject();
try {
json.putOpt("userid", StorePreference.GetSharedPreferenceDetails(context, "memberid"));
json.putOpt("rid",StorePreference.GetSharedPreferenceDetails(context, "partnerid"));
json.putOpt("message", "Received");
BoundService.getInstance().onlinestatus(json);
} catch (Exception e) {
e.printStackTrace();
}
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Manifest decleration:
<receiver
android:name="com.twogether.receivers.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name = "com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
</receiver>
Try to register your receiver in manifest, use GcmListenerService to receive messages.
google example https://github.com/googlesamples/google-services has example to do this.
<!-- gcm_receiver, this is android source-->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.myapp.gcm" />
</intent-filter>
</receiver>
<!-- gcm_listener service -->
<service
android:name="com.qblinks.qmote.GcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
// Use this service to receive message
public class GcmListenerService extends com.google.android.gms.gcm.GcmListenerService {
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.v(TAG, "From: " + from);
Log.v(TAG, "Message: " + message);
sendNotification(message);
}
private void sendNotification(String message) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification)
.setContentTitle("this is title")
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))//multi line
.setSound(defaultSoundUri); // ring or vibrate if no ring
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Const.NOTIFICATION_GCM /* ID of notification */, notificationBuilder.build());
}
}
When the app is close you need to wake the app up, means you need to have the permission to do that
<uses-permission android:name="android.permission.WAKE_LOCK" />
and after you can set:
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, yourIntent);