Android Notification not shown - android

I wrote an IntentService for GCM Push Notifications.
I receive the Messages but something's wrong with displaying my Notification to the user.
Here's my Code:
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM test";
#Override
protected void onHandleIntent(Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!intent.getExtras().isEmpty()) { // has effect of unparcelling Bundle
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + intent.getExtras().toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
sendNotification("message:\n" + intent.getStringExtra("message"));
Log.i(TAG, "Received: " + intent.getExtras().toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle("My notification")
.setContentText(msg);
Intent resultIntent = new Intent(this, PopupMessageActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(PopupMessageActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
I don't see the mistake. I mean, I copied the code from the Androids developer guide.
The only thing that this code does, is that the small icon (in this case "ic_notif") is showing in the notification-bar of the phone.
But there's no Text or Notification that pops up to the user.
I use android-studio.
My debug device is an huawai u8666e with android 4.0.3 (API 15).
At least i want this API level to be my minimum requirement for this app.

What you are seeing is normal designed Android behaviour for versions before Lollipop.
The design logic is that this method creates a cleaner interface and will not interrupt the user's current actions by placing a popup in front of their face. (there is a lot of debate over which method is better - iOS popups vs Android notifications).
Lollipop changes this slightly by creating a small popup at the top of the device window when a Notification is created.
If you really want to force a popup dialog to be shown, you should be looking at designing a "full screen" Notification.
See the Android Developer docs:
Notication.Builder.setFullScreenIntent(Intent)
Using this method, you can create a new Activity with any custom layout you want, and launch that instead of placing the Notification in the status bar.
(full implementation of a full screen notification would be beyond the scope of this post)
I would recommend against forcing full screen notifications except in rare cases, such as an Alarm Clock, or Phone Call app. I would, instead, recommend that you stick to the way Android was designed and work with the OS.

Related

Notifications not appearing in background state and killed state of an app

I'm trying to push notifications to the end-users of the app when post is uploaded. It works fine when the app is in foreground but doesn't show up when then the app is in background or killed. Is there any way to show the notifications when the app is killed or running in the background.
Here is the node.js code which i'm using
const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos').onWrite(event => {
var topic = "deals_notification";
let projectStateChanged = false;
let projectCreated = false;
let projectData = event.data.val();
if (((event.data.numChildren())-(event.data.previous.numChildren()))>0) {
let msg="notification arrived"
let payload = {
notification: {
title: 'Firebase Notification',
body: msg,
sound: 'default',
badge: '1'
}
};
admin.messaging().sendToTopic(topic, payload).then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
}).catch(function(error) {
console.log("Error sending message:", error);
});
}
});
and here is the MyFirebaseMessageService:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessageService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("notification---",remoteMessage.getNotification().getBody());
sendnotification(remoteMessage.getNotification().getBody());
}
private void sendnotification(String body){
Intent intent = new Intent(this, MainActivity.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, (int)
System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification.Builder n = new Notification.Builder(this)
.setContentTitle("Best Deals")
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, n.build());
}
}
Thanks.
I am sure the code is perfect. But there might be some problem with the device you are testing.Please try to test the code with some other device.
if the problem is that onMessageReceived() is called only when the app is in foreground, and when it's in background a notification is displayed but your method is not called... than that's working correctly. See the documentation:
Use notification messages when you want FCM to handle displaying a
notification on your client app's behalf. Use data messages when you
want to process the messages on your client app.
Read more here: https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
You are sending a notification-message. instead you should send a data-message
If the problem is different: when the app is in background nothing happen, it might be a problem of your device. See Push notifications using FCM not received when app is killed android

android change TextView from another class

I have GCM with php AND my code work without any problem
its idea get notification from php and show it on notification bar
and when click on notification its show me the message on TextView
i just want to update that TextView on Activity without click on notification
now let me show the code for understand me
this the home ACtivity thats contain the TextView
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Home_Activity extends Activity {
TextView view_msg;
// i try make it public static TextView view_msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
view_msg = (TextView) findViewById(R.id.message);
}
public void onResume()
{
super.onResume();
String str = getIntent().getStringExtra("msg");
if (str != null) {
view_msg.setText(str);
}
}
}
we can see its
onResume
check if there are any extra data but i want to update that TextView just when new gcm message recive
now the code that recive message
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.medo.alex.Home_Activity;
import com.medo.alex.R;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class Gcm_Notification_Intent_Service extends IntentService {
// Sets an ID for the notification, so it can be updated
public static final int notifyID = 9001;
public Gcm_Notification_Intent_Service() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("" + extras.get(Gcm_Application_Constants.MSG_KEY)); //When Message is received normally from GCM Cloud Server
}
}
Gcm_Broadcast_Receiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Intent resultIntent = new Intent(this, Home_Activity.class);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("NEW MESSAGE")
.setSmallIcon(R.mipmap.ic_launcher);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("YOU HAVE NEW MESSAGE");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
// MainActivity.view_msg.setText(msg); // iam try use this and make my view_msg public and static when i add this line and run my project and say progect name has stopped just when add this line
}
}
now my question its how to update the view_msg and its on Home_activity
when recive messgae from Gcm i write in code what i try to do but its say my project was stopped now forget my trying and just give me idea about how to update the view_msg TextView from another class
It seems like you need Service bounding
some awesome example you can find HERE
just try to bind your Activity and when it can be done just send Message with content. when Activity is missing e.g. keep Notification popping

Default push notification sound in Worklight 6.1

I'm using Worklight Push Notification but on Android the push comes with no sound. I want to enable default sound (and LED if possible).
I'm using the sample push notification example code.
var notification = WL.Server.createDefaultNotification(notificationText, badgeDigit, {custom:"data"});
I also tried to assigning a value like notification.GCM.sound = "true" or notification.GCM.sound = "default" but it is playing continuous sound on some devices.
To accomplish this you will have to modify your app. Worklight will generate a skeleton class in your Android project, GCMIntentService.java
In order to add sound and flash the LED notification light, you will have to override the notify methods in the GCMIntentService class. Your file will look like this:
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
public class GCMIntentService extends
com.worklight.androidgap.push.GCMIntentService {
#Override
public void notify(Context context, String alert, int badge, String sound,
Intent intent) {
super.notify(context, alert, badge, sound, intent);
// call helper method
notifyLightAndSound(context);
}
#Override
public void notify(Context context, String tickerText) {
super.notify(context, tickerText);
// call helper method
notifyLightAndSound(context);
}
private void notifyLightAndSound(Context context) {
// Get the default notification sound
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// build a notification with the light and sound
// LED will be on for 1000 ms and off for 800 ms until you turn on your
// screen
Notification n = new Notification.Builder(context)
.setLights(Notification.DEFAULT_LIGHTS, 1000, 800)
.setSound(notification).build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// play sound and flash LED
mNotificationManager.notify(4, n);
}
}
This will flash the LED and play the default notification sound of your phone "different based on each phone".
I hope this helps to answer your question.
LED notification is not available.
See here: Led not working on Android using Unified Push Notification of worklight (6.0.0.2)
To use a custom notification sound (see supported media formats):
If the folder does not exist already, add a folder named raw under the existing native\res folder in yourProject\apps\yourApp\android\native
Place the sound file in the raw folder
To use default notification sound, try sending it empty:
notification.GCM.sound = "";

DevicePolicyManager locknow not in an activity [duplicate]

This question already exists:
DevicePolicyManager, locknow when gcm message received
Closed 9 years ago.
Hoping someone can help me, as I have been stuck on this for days. I am trying to lock my device remotely when a PUSH notification arrives with a specified keyword. Else, display the message in a notification.
It correctly displays the notification but never locks the screen when the keyword is sent, nothing happens, nothing is logged.
I have confirmed the string is correctly read as I previously set it to display a custom notification if the message contained the keyword.
The app definitely has admin privileges and I can lock the screen using the same code inside an activity ... is there something else I need to do to get this to work in the gcmintentsevice ??
here is my gcmintentservice code
package library;
import com.test.LoginActivity;
import com.test.R;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {#code IntentService} does the actual handling of the GCM message.
* {#code GcmBroadcastReceiver} (a {#code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {#code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
String messagereceived;
String Password = "LOCK";
ComponentName mDeviceAdmin;
public static final int NOTIFICATION_ID = 1;
private DevicePolicyManager mDPM;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "test";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
messagereceived = extras.getString("message");
if(messagereceived.equals("LOCK")){
gcmaction();
}
else{
sendNotification("Message: " + extras.getString("message"));
Log.i(TAG, "Message: " + extras.toString());
}
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
//lock method
private void gcmaction() {
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdmin = new ComponentName(this, AdminReceiver.class);
boolean active = mDPM.isAdminActive(mDeviceAdmin);
if (active) {
mDPM.resetPassword(Password,DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
mDPM.lockNow();
}
else Log.i(TAG,"Not an admin");
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LoginActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ParentalKontrol")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Your my_admin.xml contains below?
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>

Android Honeycomb notification popup too frequently

I am developing for Honeycomb and for days i am trying to solve this problem.
I have an notification service without intent (don`t need one), the problem is that after every call for displaymessage function the notification pup-up each time, so i get 100 notifications. I would like it to popup only once and after that only change the text of percent. Similar to downloading from market progress bar and percentage. I have isolated the function and created new testing code but with no success. If you look at this from other angle, i wish to change the text on existing notification without creating new notification.
Can you please help me?
Here is the whole code (after the isolation):
package com.disp;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
public class DispalyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 100; i++) {
SystemClock.sleep(300);
displaymessage(""+i+"%");
}
}
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, "Notification Service", System.currentTimeMillis());
Context context = getApplicationContext();
notification.setLatestEventInfo(context, "Downloading Content:", string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, notification);
}
}
Because each notification is uniquely identified by the NotificationManager with an integer ID, you can revise the notification by calling setLatestEventInfo() with new values, change some field values of the notification, and then call notify() again.
You can revise each property with the object member fields (except for the Context and the notification title and text). You should always revise the text message when you update the notification by calling setLatestEventInfo() with new values for contentTitle and contentText. Then call notify() to update the notification. (Of course, if you've created a custom notification layout, then updating these title and text values has no effect.)
from
http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Categories

Resources