We are trying to integrate the Baidu SDK and use it together with Azure Notification Hub in the back-end.
In Android we are using the SDK: lib-techain-release-3.5.7.4
To get the PushId of the device we use:
public class BaiduReceiver extends BroadcastReceiver {
private static final int TYPE_REGISTRATION = 1;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!PUSH_ACTION.equals(action)) {
return;
}
Bundle bundle = intent.getExtras();
int type = bundle.getInt("event_type", -1);
switch (type) {
case TYPE_REGISTRATION:
String uid = bundle.getString("push_uid");
break;
default:
break;
}
}
}
Which works. This ID can be used to send push notifications from the Baidu console.
However, when integrating with Azure Notification Hub, it also requires a "Channel ID" (see https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.baiduregistrationdescription?view=azure-dotnet)
How do we obtain this channel Id in Android?
We have the information about how to integrate with Baidu here on the Get started with Notification Hubs using Baidu in particular needing to override the onBind method of the custom PushMessageReceiver class.
Related
I'm implementing GCM in Android P.
But I cannot receive the broadcasting from GCM.
What's wrong in Android P?
By the way, working well in Android O.
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.setPackage("com.google.android.gsf");
registrationIntent.putExtra("sender", sender_id);
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
public class GCMBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
Log.e("GCM", "action=" + intent.getAction() + " registration_id="+intent.getStringExtra("registration_id"));
}
}
You must be using an older version of GCM.
Upgrade to GCM 11 or higher. (The latest is 15.0.1: com.google.android.gms:play-services-gcm:15.0.1), or even better, migrate to FCM. (GCM is now deprecated)
the documentation states ...
As of April 10, 2018, Google has deprecated GCM. The GCM server and client APIs are deprecated and will be removed as soon as April 11, 2019. Migrate GCM apps to Firebase Cloud Messaging (FCM), which inherits the reliable and scalable GCM infrastructure, plus many new features. See the migration guide to learn more.
therefore, you might (sooner or later) have to migrate to FCM.
since recently, there's also Firebase In-App Messaging.
I solved this problem myself by using GCM 3.0 way like below:
public void getInstanceIdToken() {
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
public class RegistrationIntentService extends IntentService {
private static String TAG = RegistrationIntentService.class.getSimpleName();
public RegistrationIntentService() {
super(TAG);
}
String senderId = "YourSenderId";
#Override
protected void onHandleIntent(#Nullable Intent intent) {
InstanceID instanceID = InstanceID.getInstance(this);
try {
String token = instanceID.getToken(senderId,
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a chat app using Google cloud messaging. I have to migrate to FCM because of API Key. I used this tutorial: GCM to FCM but When I start the app, it closes immediately.
This is the part of Gcmintentservice. I didn't understand what I should make
Gcmintentservice.
protected void onHandleIntent(Intent intent) {
String key = intent.getStringExtra(KEY);
switch (key) {
case SUBSCRIBE:
// subscribe to a topic
String topic = intent.getStringExtra(TOPIC);
subscribeToTopic(topic);
break;
case UNSUBSCRIBE:
String topic1 = intent.getStringExtra(TOPIC);
unsubscribeFromTopic(topic1);
break;
default:
// if key is not specified, register with GCM
registerGCM();
}
}
When I delete inside of onHandleIntent function, App is working and there is no error but instant messaging is not working.
I want to take data of whatsapp message coming in my Android from Notification bar Is it possible to get this
You need to create a service to listen to incoming notifications by extending NotificationListenerService in which, you'll have a method call back :
#Override
public void onNotificationPosted(StatusBarNotification sbn) { .... }
Where you'll get all the data inside that particular notification.
If you want only WhatsApp Notifications, you can add a filter
which matches the package name like: sbn.getPackageName().matches("com.whatsapp")
Here is more information about StatusBarNotification
for getting the title/content(message) of the notifications you'll need to extract them from the bundle Bundle bundle = statusBarNotification.getNotification().extras; you can extract message from the bundle using something like this:
private String getDataFromBundle(Bundle bundle) {
Object data = bundle.get("android.bigText");
if (data == null) {
data = bundle.get("android.text");
}
return data == null? "" :data.toString();
}
PS: don't forget to register your service in manifest..
Last year when you added a Cloud Endpoints plus GCM module to an Android Studio project, the IDE created some sample code both in the backend and the app that showed how to use GCM with Cloud Endpoints.
However, with the newer versions of Android Studio you only get the backend part added for you. So I went back into my old projects and dug up some of the convenient app code which registered, and sent GCM push notifications in Android.
Here is what that code looks like:
GcmBroadcastReceiver.java
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());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GcmIntentService.java
public class GcmIntentService extends IntentService {
android.support.v4.app.NotificationCompat.Builder notification;
public GcmIntentService() {
super("GcmIntentService");
}
#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 != null && !extras.isEmpty()) { // has effect of unparcelling Bundle
// Since we're not using two way messaging, this is all we really to check for
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());
showToast(extras.getString("message"));
sendNotification(extras.getString("message"));
}
}
//call to the API and get new data.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
protected void showToast(final String message) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
private void sendNotification(String msg) {
notification = new android.support.v4.app.NotificationCompat.Builder(this);
//set number of notifications count
//notification.setNumber(x);
//cancels notification when app is opened.
notification.setAutoCancel(true);
//build the notification
notification.setSmallIcon(R.drawable.greenicon);
notification.setTicker("This is the ticker!");
//set time
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("New message!");
notification.setContentText(msg);
notification.setSound((Settings.System.DEFAULT_NOTIFICATION_URI));
//LED
notification.setLights(Color.RED, 3000, 3000);
// intent
Intent intent = new Intent(this, MainActivity.class);
//give phone access to perform this intent b/c they may be in another part of their phone.
//aka gives phone access to the intents in our app
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//what to do when notification is clicked:
notification.setContentIntent(pendingIntent);
//Builds notification and issues it (sends it to device). Can build and send out notifcations
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//send out notification with uniqueID
nm.notify(2158, notification.build());
}
}
GcmRegistrationAsyncTask
class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {
private static Registration regService = null;
private GoogleCloudMessaging gcm;
private Context context;
// TODO: change to your own sender ID to Google Developers Console project number, as per instructions above
private static final String SENDER_ID = "1026567774990";
public GcmRegistrationAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
if (regService == null) {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
// otherwise they can be skipped
.setRootUrl("https://push-notif-45657747.appspot.com/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
}) ;
// end of optional local run code
regService = builder.build();
}
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
String regId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regId;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
// The request to your server should be authenticated if your app
// is using accounts.
regService.register(regId).execute();
} catch (IOException ex) {
ex.printStackTrace();
msg = "Error: " + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Logger.getLogger("REGISTRATION").log(Level.INFO, msg);
}
}
However, I am getting some deprecated errors in Android Studio now:
gcm.register(SENDER_ID); is deprecated and so is GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.
This GCM stuff is pretty confusing to begin with and while there is some information here on how to use it, I was wondering if anyone had any currently working non-deprecated examples or maybe you could suggest some edits to the above code if you know what you are doing...? Much thanks!
Wanted to give people a little guide here in case they were lost.
First check out and stay up to date with this Google Cloud Messaging Android example:
https://github.com/google/gcm
To make it work you will have to generate a google-services.json file which you can do here:
https://developers.google.com/mobile/add
Make sure you are logged into the google developers console before you go that link. It will load your projects for you and automatically set up the gcm api key for you in your projects credentials.
Copy/paste the google-services.json into the /app directory of your Android project.
Add a cloud endpoints with gcm module to the android project.
Enter your gcm api key (which you can view on your credentials page on developers console) into the webapp-WEB_INF/appengine-web.xml file in your cloud endpoints backend:
<property name="gcm.api.key" value="your-api-key-here"/>
This way, inside the Android client and MessagingEndpoint the code will automatically get the api key (in the endpoint it will be the line Sender sender = new Sender(API_KEY); for example, which will just retrieve it for you).
Run the sample gcm android project and it should work. Send a push notification with the API's explorer you deployed.
BIG NOTE: when you are ready to use the sample code in your own app make sure the RegistrationIntentService is in the root of your package or it won't work! Took a while to figure that out... Not sure if it is a bug or what.
I want to implement push notification in Android using Phonegap. I have successfully created an app using https://github.com/marknutter/GCM-Cordova.
I have also created my app id and sender id using https://code.google.com/apis/console/.
Can anyone suggest where I should put these keys in my project?
I also use the plugin.
Not sure about the app id, but the send ID you pass in the function for registering:
GCM.register(STRING_YOUR_SENDER_ID, "GCM_Event", GCM_Success, GCM_Fail );
Check the GCM documentation here, here is a code snippet (I modified a bit from the original example in the documentation):
public class GCMIntentService extends GCMBaseIntentService {
private static final String SENDER_ID = ""; // Your project ID from the API Console
public GCMIntentService() {
super(SENDER_ID);
}
#Override
public void onCreate() {
super.onCreate();
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
}
#Override
protected void onError(Context context, String error) {
}
#Override
protected void onMessage(Context context, Intent message) {
//String value = message.getExtras().getString("message");
}
#Override
protected void onRegistered(Context context, String resId) {
// You should save the resId to use it when sending a message from your server
}
#Override
protected void onUnregistered(Context arg0, String msg) {
// Delete the resId from your server
}
}
To test it you need first to call the above service to register your device with GCM service (and get a registration id that you will use when sending the message), you can do something like:
Intent registrationIntent = new Intent(
"com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app",
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// registrationIntent.putExtra("sender", "Your sender id"); // Better than keep the sender id hard coded in the service
context.startService(registrationIntent);
To send a message you can have a simple Java application as below (you can do it from other languages as well):
public static void sendMessage(String msg) throws IOException {
String myApiKey = "Your Browser API Key";
String regId = "Registeration id"; // the value you received in
// onRegistered() in the above
// onRegistered class
Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().addData("message", msg).build();
Result result = sender.send(message, regId, 5); // 5 is the maximum number of trials to deliver your message
if (result.getMessageId() != null) {
System.out.println("Message sent");
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// This means that the registration id got updated, so use the new one for future messages
System.out.println("canonicalRegId: " + canonicalRegId);
}
} else {
System.out.println("error: " + result.getErrorCodeName());
}
}
use the plugin
cordova plugin add phonegap-plugin-push --variable SENDER_ID="XXXXXXX"
replace the xxxxxx with your sender id
sender id is the project id/project number in google console
in your javascript add the following code for registering
var push = PushNotification.init({
android: {
senderID: "XXXXXXXX" //add your sender id here
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
});
push.on('registration', function(data) {
consol.log(data.registrationId); //this function give registration id from the GCM server if you dont want to see it please comment it
document.getElementById("gcm_id").value= data.registrationId; //showing registration id in our app. If it shows our registration process is suscess
//$("#gcm_id").val(data.registrationId); if you are using jquery
});
if you want to get more detail in how to implement push notification in cordova please go through the following link
http://phonegaptut.com/2016/05/31/how-to-send-push-notifications-in-phonegap-application/