Send data to activity when Firebase notification is clicked in Android - java

In my application I want use fireBase for notification.
I want when click on notification (when app is closed, my mean is app is background) send data with putExtra to mainActivity.
I write below codes, but when click on notification (in app is background) but show me null for getStringExtra !
MyNotificationManager class :
public class MyNotificationManager {
private Context mCtx;
private Uri soundUri;
private static MyNotificationManager mInstance;
public MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(mCtx, MainActivity.class);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setContentText(body)
.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
MyFirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void showNotify(String title, String body) {
MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
//myNotificationManager.displayNotification(title, body);
myNotificationManager.displayNotification(title, body);
}
}
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkIntent()) return;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkIntent();
}
}, 1000);
}
private boolean checkIntent() {
String value = getIntent().getStringExtra("fcm_notification");
Toast.makeText(context, "" + value, Toast.LENGTH_SHORT).show();
if (value == null) return false;
if (value.equals("Y")) {
startActivity(new Intent(this, LandingActivity.class));
// open one activity.
} else if (value.equals("another thing")) {
// open another activity.
}
finish();
return true;
}
When click on notification (on app is background) , show me null message in Toast for this line String value = getIntent().getStringExtra("fcm_notification");
How can i fix it?

When sending notification from console, add the custom data from 'Advanced options':
For some reason, firebase doesn't allow the key to start with fcm. You cannot use fcm_notification. Use a different key.
For above image, receive the key as follows:
String value = getIntent().getStringExtra("test_key");

Try this:
Intent intent = new Intent(mCtx, MainActivity.class);
intent.putExtra("EXTRA_DATA", title);
And to get:
String value = getIntent().getStringExtra("EXTRA_DATA");
Better to change the key. Also, it seems like you'll need to send a data from console and then, sending the data to the another Activity.
I've used the current notification title to check if it returns the title or not.If it returned the value, so, try sending data from the console.

Related

Arraylist being assigned correctly inside a constructor but is null when it is outside in a Android Studio Service

I cannot seem to figure out as to why whenever I try to assign an arraylist I recieved from the MainActivity to a public arraylist of a background service SensorService in the service's constructor.
This is my constructor
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
I even tried invoking a method but it still gives me the same results where it assigns the contactNumbers correctly but when I try to invoke it inside onCreate I get an NullPointerException.
This is the MainActivity Intent where I create the service
SensorService sensorService = new SensorService(Contact_Number);
Intent intent = new Intent(this, sensorService.getClass());
if(!isMyServiceRunning(sensorService.getClass())){
startService(intent);
//intent.putExtra("ContactNumberList", Contact_Number);
Toast.makeText(this, "Starting Service", Toast.LENGTH_SHORT).show();
}
And this is my complete SensorService.
public class SensorService extends Service {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public ArrayList<String> contactNumbers;
public SensorService() {
}
public SensorService(ArrayList<String> contactListNumber) {
contactNumbers=contactListNumber;
Log.d(TAG, "Inside Constructor");
Log.d(TAG, "SensorService: Phone Numbers = "+contactListNumber);
Log.d(TAG, "SensorService: Input Arraylist Size = "+contactListNumber.size());
Log.d(TAG, "SensorService: Assigned Arraylist Size = "+contactNumbers.size());
setPhoneNumberArray(contactListNumber);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
//contactNumbers=MainActivity.Contact_Numbers;
super.onCreate();
// start the foreground service
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
Log.d(TAG, "SensorService: Assigned Arraylist Size Outside Constructor = "+contactNumbers.size());
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#SuppressLint("MissingPermission")
#Override
public void onShake(int count) {
// check if the user has shacked
// the phone for 3 time in a row
//if (count == 3)
if (count == 1) {
// vibrate the phone
vibrate();
Log.d(TAG, "onShake: Vibrate Activated");
// create FusedLocationProviderClient to get the user location
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
Log.d("Check: ", "Sending Message");
// use the PRIORITY_BALANCED_POWER_ACCURACY
// so that the service doesn't use unnecessary power via GPS
// it will only use GPS at this very moment
fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() {
#Override
public boolean isCancellationRequested() {
return false;
}
#NonNull
#Override
public CancellationToken onCanceledRequested(#NonNull OnTokenCanceledListener onTokenCanceledListener) {
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// check if location is null
// for both the cases we will
// create different messages
Log.d("Check: ", "MESSAGE SENT");
if (location != null) {
// get the SMSManager
SmsManager smsManager = SmsManager.getDefault();
// get the list of all the contacts in Database
DatabaseHelper db = new DatabaseHelper(SensorService.this);
ArrayList<String> Contact_id, Contact_Name, Contact_Number;
ArrayList<String> phonenumber = new ArrayList<String>();
Log.d(TAG, "onSuccess: contactlistnumber size = "+contactNumbers.size());
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
Log.d(TAG, "onSuccess: Item 1 = "+phoneNumberList[0]);
for(int i = 0; i < phoneNumberList.length ; i++){
Log.d("Number is",(String)phoneNumberList[i]);
}
//phonenumber = (ArrayList<String>)getIntent().getSerializableExtra("ContactNumberList");
// send SMS to each contact
for (String c : phoneNumberList) {
String message = "Hey, I am in DANGER, i need help. Please urgently reach me out. Here are my coordinates.\n " + "http://maps.google.com/?q=" + location.getLatitude() + "," + location.getLongitude();
smsManager.sendTextMessage(c, null, message, null, null);
}
} else {
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList) {
smsManager.sendTextMessage(c, null, message, null, null);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Check: ", "OnFailure");
String message = "I am in DANGER, i need help. Please urgently reach me out.\n" + "GPS was turned off.Couldn't find location. Call your nearest Police Station.";
SmsManager smsManager = SmsManager.getDefault();
DatabaseHelper db = new DatabaseHelper(SensorService.this);
List<ContactInfo> list = (List<ContactInfo>) db.getEveryone();
String[] phoneNumberList = new String[contactNumbers.size()];
phoneNumberList = contactNumbers.toArray(phoneNumberList);
for (String c : phoneNumberList){
smsManager.sendTextMessage(c, null, message, null, null);
}
}
});
}
}
});
// register the listener
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
// method to vibrate the phone
public void vibrate() {
final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
VibrationEffect vibEff;
// Android Q and above have some predefined vibrating patterns
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibEff = VibrationEffect.createPredefined(VibrationEffect.EFFECT_DOUBLE_CLICK);
vibrator.cancel();
vibrator.vibrate(vibEff);
} else {
vibrator.vibrate(500);
}
}
// For Build versions higher than Android Oreo, we launch
// a foreground service in a different way. This is due to the newly
// implemented strict notification rules, which require us to identify
// our own notification channel in order to view them correctly.
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("You are protected.")
.setContentText("We are there for you")
// this is important, otherwise the notification will show the way
// you want i.e. it will show some default notification
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
// create an Intent to call the Broadcast receiver
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
public void setPhoneNumberArray(ArrayList numbers) {
contactNumbers=numbers;
//Log.d(TAG, "setPhoneNumberArray: contactnumbers size = "+contactNumbers.size());
}
}
would really appreciate if anyone could tell me why this is happening.
I found my mistake.
For anyone else trying to do this.
I made the very shortsighted mistake of not declaring the Arraylist contactNumbers as static.
This is what it looked like before.
public ArrayList<String> contactNumbers;
In the end when I added the static keyword. such that it looks like
static public ArrayList<String> contactNumbers;.
Everything else seems to work corrrectly. Since I could now get the value of contactNumbers inside of the service.

Android - How can I update data or UI in my Activity when Push Notification FCM is received?

I have the following FirebaseMessagingService which works fine when I get a push notification and the app is in foreground:
public class _FCMService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// Log.i(TAG, "PUSH PAYLOAD: " + remoteMessage.getData());
JSONObject pushData = new JSONObject(remoteMessage.getData());
pushType = pushData.optString("pushType");
pushMessage = pushData.optString("body");
Log.i(TAG, "ON PUSH RECEIVED - pushType: " + pushType);
Log.i(TAG, "ON PUSH RECEIVED - pushMessage: " + pushMessage);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentText(pushMessage)
.setStyle(new NotificationCompat.BigTextStyle())
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(0 , notificationBuilder.build());
}
}
#Override
public void onNewToken(#NotNull String token) {
Log.i(TAG, "Refreshed token: " + token);
ANDROID_DEVICE_TOKEN = token;
}
}
So, If I receive a push, the Logcat prints out the notification's body and (if present) the pushType string.
What I would need to do is to make my other Activity update data when push is received, as well as get the pushMessage and pushType strings.
I know how to do that in iOS Swift - by using NotificationCenter - but have no idea about Android, I've tried LocalBroadcaster, but no success.
LocalBroadcastManager is now deprecated!
You can use LiveData implementation in a static reference and observe it in the Activity or Fragment
public class NotificationService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Notification.
getInstance().
addOrder(remoteMessage.getData().get("id"));
}
public static class Notification {
private static Notification instance;
private MutableLiveData<String> newOrder;
private Notification() {
newOrder = new MutableLiveData<>();
}
public static Notification getInstance() {
if(instance == null){
instance = new Notification();
}
return instance;
}
public LiveData<String> getNewOrder() {
return newOrder;
}
public void addOrder(String orderID){
newOrder.postValue(orderID);
}
}
}
And In the Activity or Fragment:
NotificationService.
Notification.
getInstance().
getNewOrder().
observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(String s) {
//TODO: update your ui here...
}
});
You can add a .setContentIntent(NotificationChannelUtil.createPendingIntent(this, pushMessage, pushType)) to your notificaitionBuilder.
Where that function is inside an util class like:
public class NotificationChannelUtil {
private NotificationChannelUtil() {}
public static PendingIntent createPendingIntent(Context context, String pushMessage, String pushType) {
Intent intent = new Intent(context, YourWantedActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("pushMessage", pushMessage);
intent.putExtra("pushType", pushType);
return PendingIntent.getActivity(context, 0 /* request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
}
}
I've found a solution to my issue, which actually looks similar to the iOS NotificationCenter instance. I've added this class into my _FCMService.java file:
class NotificationCenter {
private static NotificationCenter _instance;
private HashMap<String, ArrayList<Runnable>> registredObjects;
private NotificationCenter(){
registredObjects = new HashMap<>();
}
//returning the reference
static synchronized NotificationCenter defaultCenter(){
if(_instance == null)
_instance = new NotificationCenter();
return _instance;
}
synchronized void addFunctionForNotification(String notificationName, Runnable r){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list == null) {
list = new ArrayList<Runnable>();
registredObjects.put(notificationName, list);
}
list.add(r);
}
public synchronized void removeFunctionForNotification(String notificationName, Runnable r){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list != null) {
list.remove(r);
}
}
synchronized void postNotification(String notificationName){
ArrayList<Runnable> list = registredObjects.get(notificationName);
if(list != null) {
for(Runnable r: list)
r.run();
}
}
}
Then I've called it inside the onMessageReceived() function:
NotificationCenter.defaultCenter().postNotification("pushNotif");
Lastly, I've added the observer into the onStart() function of my Activity as it follows:
#Override
protected void onStart() {
super.onStart();
// Start NotificationCenter to observe for new messages
NotificationCenter.defaultCenter().addFunctionForNotification("pushNotif", new Runnable() {
#Override
public void run() {
Log.i(TAG, "Obj Details -> pushMessage: " + pushMessage + "\npushType" + pushType);
}});
}
It works smoothly, hoper this helps somebody else.

android fcm notification not received

android fcm notification not received and while the device which supposed to receivethe notification shows this message in Logcat (Received from FCM TITLE: null, Received from FCM BODY: null). I have already checked that notification is not being received in both <26 and >26 SDK Versions
====================MyFirebaseMessagingService===============================
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String channel_id = "the_id";
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
updateTokenToFirebase(s);
}
private void updateTokenToFirebase(String token) {
IDrinkShopAPI mService = Common.getAPI();
mService.updateToken("SERVER_01",token,"0")
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("DEBUG_TOKEN",response.body());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("DEBUG_TOKEN",t.getMessage());
}
});
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getData() != null){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
sendNotification26(remoteMessage);
else
sendNotification(remoteMessage);
}
}
private void sendNotification26(RemoteMessage remoteMessage) {
Map<String,String> data = remoteMessage.getData();
String title = data.get("title");
String message = data.get("message");
NotificationHelper helper ;
Notification.Builder builder;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
helper = new NotificationHelper(this);
builder = helper.getDrinkShopNotification(title,message,defaultSoundUri);
helper.getManager().notify(new Random().nextInt(),builder.build());
}
private void sendNotification(RemoteMessage remoteMessage) {
Map<String,String> data = remoteMessage.getData();
String title = data.get("title");
String message = data.get("message");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri);
NotificationManager mn =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mn.notify(new Random().nextInt(),builder.build());
}
}
=========================NotificationHelper =================================
//this class is used to implement notification for all android versions
public class NotificationHelper extends ContextWrapper {
private static final String CHANNEL_ID = "the_id";
private static final String CHANNEL_NAME = "Drink_Shop";
private NotificationManager notificationManager;
public NotificationHelper(Context base) {
super(base);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannel();
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel nc = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
nc.enableLights(false);
nc.enableVibration(true);
nc.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(nc);
}
public NotificationManager getManager() {
if(notificationManager == null)
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
}
#TargetApi(Build.VERSION_CODES.O)
public Notification.Builder getDrinkShopNotification(String title,
String message,
Uri soundUri)
{
return new Notification.Builder(getApplicationContext(),CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(soundUri)
.setChannelId(CHANNEL_ID)
.setAutoCancel(true);
}
}
=============================Manifest=======================================
<service
android:name=".Services.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
============================Build.gradle====================================
implementation 'com.google.firebase:firebase-messaging:20.0.0'
implementation 'com.google.firebase:firebase-core:17.2.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
===========================IFCMService=======================================
public interface IFCMService {
#Headers({
"Content-Type:application/json",
"Authorization:mytoken"
})
#POST("fcm/send")
Call<MyResponse> sendNotification(#Body DataMessage body);
}
==========================sendNotificationToServer===============================
// this method used to send the notification to server device
private void sendNotificationToServer(OrderResult orderResult) {
mService.getToken("SERVER_01", "1")
.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
Map<String,String> contentSend = new HashMap<>();
contentSend.put("title","NEW ORDER");
contentSend.put("message","You have got new order" + orderResult.getOrderId());
DataMessage dataMessage = new DataMessage();
if(response.body().getToken() != null)
dataMessage.setTo(response.body().getToken());
dataMessage.setData(contentSend);
IFCMService ifcmService = Common.getFCMService();
ifcmService.sendNotification(dataMessage)
.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if(response.code() == 200){
if(response.body().success == 1){
Toast.makeText(CartActivity.this,
getResources().getString(R.string.order_submitted), Toast.LENGTH_SHORT)
.show();
//Clear Carts From Room Database
Common.cartRepository.emptyCart();
//finish();
}
else {
Toast.makeText(CartActivity.this, "Send Notification Failed", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(CartActivity.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Toast.makeText(CartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have solved this issue by downgrading firebase-messaging library as follow (implementation 'com.google.firebase:firebase-messaging:17.3.4') as will as .setColor(ContextCompat.getColor(this, R.color.colorAccent)) in NotificationCompat. However this has solved the issue for me for SDK version lower than 26. Anyone knows why it is still cashing on APIs higher than 26 ?! help me please
When the App is running in background the notification is received in the system tray, and when is tapped, the intent is sended to your activity default, with the notification with payload of content of it.
When your application is running in front, the notification is received with the FirebaseMessagingService and the logic that you overrided.
I think you should add the logic of the first point, when the app is running in background
Check here more information
Handling messages

Lock Screen Player Controls and Meta Data

I'm trying to use MediaSessionCompat in order to add lock screen player controls and meta data for my app. Everything I tried doesn't work. The lock screen doesn't show any controls or meta data while playing. Please see my current code below and any help is appreciated.
StreamService.java:
public class StreamService extends Service implements MediaPlayer.OnCuePointReceivedListener, MediaPlayer.OnStateChangedListener,
MediaPlayer.OnInfoListener, AudioManager.OnAudioFocusChangeListener {
private WifiManager.WifiLock wifiLock;
private static String LOG_TAG = "StreamService";
public static final String BROADCAST_PLAYER_STATE = "com.test.BROADCAST_PLAYER_STATE";
public static final String BROADCAST_PLAYER_META = "com.test.BROADCAST_PLAYER_META";
public static final String BROADCAST_PLAYER_ALBUM = "com.test.BROADCAST_PLAYER_ALBUM";
public static final int NOTIFICATION_ID = 999999;
private MediaSessionCompat mediaSession;
private boolean audioInterrupted = false;
public StreamService() {
}
#Override
public void onCreate(){
super.onCreate();
setupMediaPlayer();
setupMediaSession();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public boolean onUnbind(Intent intent){
releasePlayer();
return false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
private void setupMediaPlayer() {
// Recreate player
Bundle playerSettings = (BrandedApplication.getContext().getmTritonPlayer() == null) ? null : BrandedApplication.getContext().getmTritonPlayer().getSettings();
Bundle inputSettings = createPlayerSettings();
if (!Utility.bundleEquals(inputSettings, playerSettings)) {
releasePlayer();
createPlayer(inputSettings);
}
// Start the playback
play();
}
private void setupMediaSession() {
ComponentName receiver = new ComponentName(getPackageName(), RemoteReceiver.class.getName());
mediaSession = new MediaSessionCompat(this, "StreamService", receiver, null);
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, 0, 0)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE)
.build());
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "Test Artist")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "Test Album")
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Test Track Name")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 10000)
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, "Test Artist")
.build());
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
// Ignore
}
}, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mediaSession.setActive(true);
}
synchronized private void play() {
audioInterrupted = false;
BrandedApplication.getContext().getmTritonPlayer().play();
if(wifiLock != null) {
wifiLock.acquire();
}
if(mediaSession != null) {
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
}
}
synchronized private void stop() {
BrandedApplication.getContext().getmTritonPlayer().stop();
if(wifiLock != null) {
wifiLock.release();
}
if(mediaSession != null) {
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, 0, 0.0f)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
}
}
private void createPlayer(Bundle settings)
{
BrandedApplication.getContext().setmTritonPlayer(new TritonPlayer(this, settings));
wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
BrandedApplication.getContext().getmTritonPlayer().setOnCuePointReceivedListener(this);
BrandedApplication.getContext().getmTritonPlayer().setOnInfoListener(this);
BrandedApplication.getContext().getmTritonPlayer().setOnStateChangedListener(this);
}
protected void releasePlayer() {
if (BrandedApplication.getContext().getmTritonPlayer() != null) {
if(BrandedApplication.getContext().isPlaying()) {
stop();
}
BrandedApplication.getContext().getmTritonPlayer().release();
BrandedApplication.getContext().setmTritonPlayer(null);
}
stopForeground(true);
}
protected Bundle createPlayerSettings() {
// Player Settings
Bundle settings = new Bundle();
// AAC
settings.putString(TritonPlayer.SETTINGS_STATION_MOUNT, getResources().getString(R.string.station_stream_mount) + "AAC");
// MP3
//settings.putString(TritonPlayer.SETTINGS_STATION_MOUNT, mountID);
settings.putString(TritonPlayer.SETTINGS_STATION_BROADCASTER, getResources().getString(R.string.app_name));
settings.putString(TritonPlayer.SETTINGS_STATION_NAME, getResources().getString(R.string.app_name));
return settings;
}
#Override
public void onCuePointReceived(MediaPlayer mediaPlayer, Bundle bundle) {
//System.out.println("TRITON PLAYER BUNDLE " + bundle);
String trackName = "";
String artistName = "";
if(bundle != null) {
if(bundle.containsKey("cue_title") && bundle.containsKey("track_artist_name")) {
if (!bundle.getString("cue_title").isEmpty()) {
trackName = bundle.getString("cue_title");
}
if (!bundle.getString("track_artist_name").isEmpty()) {
artistName = bundle.getString("track_artist_name");
}
}
}
// broadcast out the meta data
Intent i = new Intent(BROADCAST_PLAYER_META);
i.putExtra("trackName", trackName);
i.putExtra("artistName", artistName);
sendBroadcast(i);
// send notification and start as foreground service
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
String tickerString = "";
String contentString = "Playing";
if(!artistName.isEmpty() && !trackName.isEmpty()) {
tickerString = artistName + " - " + trackName;
contentString += ": " + artistName + " - " + trackName;
}
Intent pauseIntent = new Intent(BROADCAST_PLAYER_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(tickerString)
.setContentText(contentString)
.setSmallIcon(R.drawable.ic_launcher)
//.setAutoCancel(true)
//.setLargeIcon(
// Bitmap.createScaledBitmap(icon, 128, 128, false))
.addAction(R.drawable.ic_media_pause, "Pause", pausePendingIntent)
.setContentIntent(pi)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
//.setShowActionsInCompactView(0)
.setMediaSession(mediaSession.getSessionToken()))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true);
//notification.setPriority(Notification.PRIORITY_MIN);
notification.setPriority(Notification.PRIORITY_DEFAULT);
startForeground(NOTIFICATION_ID, notification.build());
}
#Override
public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {
}
#Override
public void onStateChanged(MediaPlayer mediaPlayer, int state) {
Log.i(LOG_TAG, "onStateChanged: " + TritonPlayer.debugStateToStr(state));
// broadcast out the player state
Intent i = new Intent(BROADCAST_PLAYER_STATE);
i.putExtra("state", state);
sendBroadcast(i);
}
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
System.out.println("AUDIO FOCUS GAIN");
if(audioInterrupted) {
audioInterrupted = false;
if (BrandedApplication.getContext().getmTritonPlayer() == null) {
setupMediaPlayer();
} else if (!BrandedApplication.getContext().isPlaying()) {
setupMediaPlayer();
}
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS:
System.out.println("AUDIO FOCUS LOSS");
// Lost focus for an unbounded amount of time: stop playback and release media player
if (BrandedApplication.getContext().isPlaying()) {
audioInterrupted = true;
releasePlayer();
}
break;
}
}
#Override
public void onDestroy() {
System.out.println("SERVICE STOPPED");
releasePlayer();
mediaSession.release();
}
}
And here's RemoteReceiver.java:
public class RemoteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
context.startService(new Intent(context, StreamService.class));
break;
}
}
}
}
}
Okay, from the additional information you provided, I believe I know what the issue is. In Android 5.0 Lock Screen Controls were removed. They are now implemented via the Notification API. So try adding the following to your notification builder.
notification.setStyle(new NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0)
.setMediaSession(mediaSession));
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
That should place it on your lock screen. I would also suggest changing the Notification.PRIORITY_DEFAULT as well as include an action to your notification otherwise you won't be able to control the playback.
I know this post is late but if anyone is still facing the issue.This will show up in your lock screen also.
Here is the code for notification builder class-
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.session.MediaSessionManager;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import org.json.JSONException;
public class MediaPlayerService extends Service {
private static final String CHANNEL_ID = "my_channel_01";
public static final String ACTION_PLAY = "action_play";
public static final String ACTION_PAUSE = "action_pause";
public static final String ACTION_NEXT = "action_next";
public static final String ACTION_PREVIOUS = "action_previous";
public static final String ACTION_STOP = "action_stop";
public static final String ACTION_NOTHING = "action_previous";
private NotificationManager notificationManager;
NotificationManager mNotificationManager;
private MediaPlayer mMediaPlayer;
private MediaSessionManager mManager;
private MediaSessionCompat mSession;
private MediaControllerCompat mController;
private MediaPlayerService mService;
String title = null;
String description = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void handleIntent(Intent intent) {
if (intent == null || intent.getAction() == null)
return;
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_PLAY)) {
mController.getTransportControls().play();
} else if (action.equalsIgnoreCase(ACTION_PAUSE)) {
mController.getTransportControls().pause();
} else if (action.equalsIgnoreCase(ACTION_PREVIOUS)) {
mController.getTransportControls().skipToPrevious();
} else if (action.equalsIgnoreCase(ACTION_NEXT)) {
mController.getTransportControls().skipToNext();
} else if (action.equalsIgnoreCase(ACTION_STOP)) {
mController.getTransportControls().stop();
}
}
private NotificationCompat.Action generateAction(int icon, String title, String intentAction) {
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(intentAction);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}
#SuppressLint("ServiceCast")
private void buildNotification(NotificationCompat.Action action) {
title = ""; // add variable to get current playing song title here
description =""; // add variable to get current playing song description here
Intent notificationIntent = new Intent(getApplicationContext(), HomeActivity.class); //specify which activity should be opened when widget is clicked (other than buttons)
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Notification channels are only supported on Android O+.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
//method to create channel if android version is android. Descrition below
createNotificationChannel();
}
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(ACTION_STOP);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
final NotificationCompat.Builder builder;
//condition to check if music is playing
//if music is playing widget cant be dismissed on swipe
if(<add your method to check play status here>)
{
builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo2b)
.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(description)
.setDeleteIntent(pendingIntent)
.setContentIntent(contentIntent)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setColor(getResources().getColor(R.color.colorPrimary))
.setOngoing(true) //set this to true if music is playing widget cant be dismissed on swipe
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
// show only play/pause in compact view
.setShowActionsInCompactView(0, 1, 2));
}
//else if music is not playing widget can be dismissed on swipe
else
{
builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo2b)
.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(description)
.setDeleteIntent(pendingIntent)
.setContentIntent(contentIntent)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setColor(getResources().getColor(R.color.colorPrimary))
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
// show only play/pause in compact view
.setShowActionsInCompactView(0, 1, 2));
}
builder.addAction(generateAction(R.drawable.ic_skip_previous_white_24dp, "Previous", ACTION_PREVIOUS));
builder.addAction(action);
builder.addAction(generateAction(R.drawable.ic_skip_next_white_24dp, "Next", ACTION_NEXT));
//style.setShowActionsInCompactView(0,1,2);
// builder.setColor(getResources().getColor(R.color.app_orange_color));
notificationManager.notify(1, builder.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mManager == null) {
try {
initMediaSessions();
} catch (RemoteException e) {
e.printStackTrace();
}
}
handleIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
private void initMediaSessions() throws RemoteException {
mMediaPlayer = new MediaPlayer();
mSession = new MediaSessionCompat(getApplicationContext(), "simple player session");
mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());
mSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
super.onPlay();
//add you code for play button click here
//replace your drawable id that shows pauseicon buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onPause() {
super.onPause();
//add you code for pause button click here
//replace your drawable id that shows play icon buildNotification(generateAction(R.drawable.uamp_ic_play_arrow_white_24dp, "Play", ACTION_PLAY));
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
//add you code for next button click here
buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
//add you code for previous button click here
buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onStop() {
super.onStop();
Log.e("MediaPlayerService", "onStop");
//Stop media player and dismiss widget here
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(1);
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
stopService(intent);
}
#Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
}
}
);
}
#Override
public boolean onUnbind(Intent intent) {
mSession.release();
return super.onUnbind(intent);
}
//method to create notification channel on android Oreo and above
#RequiresApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
int notifyID = 1;
CharSequence name = "Player Widget";// The user-visible name of the channel. This channel name will be shown in settings.
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel notificationChannel =
new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
And fire these intents for actions to update widget when play status is changed from within the app:
Play-
//to change widgets current action button to play
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);
Pause-
//to change widgets current action button to pause
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PLAY);
startService(intent);
Excuse me if there are any unwanted import.All the best.

Android Handheld and Wear Communication is not consistent

We have an Android mobile app, where you can purchase parking tickets for a period. Now, we are planning to integrate it with Android wear.
What we are doing here is:
We want the user to get notified 15 before of the expiry of ticket.
To do this, we create a local notification and schedule it using Alarm Manger.
This scheduled notification is received by Android Broadcast receiver and display this notification on mobile device in Android notification section.
Further, this receiver calls the intent service to send the notification to wear. In this step, we create googleApiClient and onConnected callback, we send the data to wear to show the notification.
On wear, user can check the notification and on tap, user can extend the time of purchased ticket. This flow contains 3-4 views after notification tapping.
We have issue in step 4. Most of the time, on a very first connection (notification), wear does not show the notification and on second connection (notification), wear show both first and second notification and after that it works fine.
We tried to figure out the problem, but no success. Below is the code snippet of Receiver, Intent Service and wear side ListnerServices for understanding.
public class WearNotificationService extends IntentService {
private static final String TAG = "PhoneActivity";
private GoogleApiClient mGoogleApiClient;
public static String title;
public static String desc;
public static String data;
public WearNotificationService() {
super("WearNotificationService");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, title +"--"+ desc , Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
sendNotification(title,desc,data);
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
}).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onHandleIntent(Intent intent) {
}
private void sendNotification(String title,String desc,String data) {
Log.e(TAG, "i am onConnectiond: ");
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(Constants.PATH_NOTIFICATION);
dataMapRequest.getDataMap().putDouble(Constants.NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
dataMapRequest.getDataMap().putString(Constants.KEY_TITLE, title);
dataMapRequest.getDataMap().putString(Constants.KEY_DESC, desc);
dataMapRequest.getDataMap().putString(Constants.KEY_DATA, data);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
String action = intent.getAction();
if (Constants.ACTION_DISMISS.equals(action)) {
dismissNotification();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
if (Constants.PATH_NOTIFICATION.equals(dataEvent.getDataItem().getUri().getPath())) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(dataEvent.getDataItem());
String title = dataMapItem.getDataMap().getString(Constants.KEY_TITLE);
String content = dataMapItem.getDataMap().getString(Constants.KEY_DESC);
String data = dataMapItem.getDataMap().getString(Constants.KEY_DATA);
String id = null;
try {
JSONObject obj = new JSONObject(data);
id = (String) obj.get("id");
} catch (JSONException e) {
e.printStackTrace();
}
sendNotification(title, content, data,id);
}
}
}
}
private void sendNotification(String title, String content, String data,String id) {
Intent notificationIntent = new Intent(this, HoursExtension.class);
Log.e("data1111", data);
HoursExtension.data = data;
HoursExtension.id = id;
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(notificationPendingIntent)
.extend(new NotificationCompat.WearableExtender().setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.rtabg)))
;
Notification notification = builder.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(Integer.parseInt(id), notification);
}
I solved it by sending a dummy request on app installation . Which is send once the app is installed and handled in wear by eating that first request this solved my problem . :)

Categories

Resources