How to do push notification from server to android mobile - android

I don't know anything about push notification. I am trying to learn. but I don't understand.
I have one table MySQL database in server system. When any changes are made in the table I want display notification on an android mobile app.
Can anyone provide any suggestions?

actually now recently mostly use for push notification FCM inside that u project ....
best link for build the push notication: link
steps for perform push notification -
Firebase Cloud Messaging Tutorial for Android
Go to firebase console and create a new project.
Now put your app name and select your country.
Now click on Add Firebase to Your Android App.
Now you have to enter your projects package name and click on ADD APP.
After clicking add app you will get google-services.json file.
On App side
Now come back to your android project. Go to app folder and paste google-services.json file
Now go to your root level build.gradle file and add the following code.
a. Add this line
classpath 'com.google.gms:google-services:3.0.0'
b. Add this line
compile 'com.google.firebase:firebase-messaging:9.0.0'
Now sync your project.
Create a class named MyFirebaseInstanceIDService.java and write the following code:
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 on logcat
Log.d(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
}
}
Now create MyFirebaseMessagingService.java and write the following code:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
*
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(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("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Now we have to define the above services in our AndroidManifest.xml file. So go to manifest and modify as follows.
<!-- Adding Internet Permission -->
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
Defining Services
-->
<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>
finally
Go to firebase console and select the app you created.
From the left menu select notification.
Click on new message.
Enter message, select single device and paste the token you copied and click on send. The same as I did on the video, and check your device

here is a good explanation about this:
http://quickblox.com/developers/SimpleSample-messages_users-android
The overall steps are:
Create a google API project
Enable push notifications for the project and get a API key
Get a registration ID through android app (each device has a registration ID for a specific application)
Create a server application to send your push messages as push notifications through google servers by GSM
Create a notification when you get the push notification on the application side
It's not something i can write all here by details. Use Google for every step.

The first thing - Google Push Notifications are called GCM (Google Cloud Messaging). Wrong name usage might lead you to wrong information or tutorial. The other thing, you should rely on Developer. In this case start from Google Developers website, where you will find most of basic info and code examples to start with. https://developers.google.com/cloud-messaging/.
Update
GCM is deprecated, you should use Firebase Cloud Messaging (FCM)

You can check out Firebase... Check out this link
https://firebase.google.com/docs/cloud-messaging/
This link is sufficient to learn about Push Notifications
And as for sending notification when data in database changes, make your API send a request to FCM server so that it delivers necessary data to clients.

Related

FCM messaging with Realtime Firebase database

My app using FireBaserealtime database and storage.Now i am struck in the part of push notification FCM.Please help anyone how to do.Is there anyway,without open firebase console and send notification to devices?Or please help me to send notification by coding.
You can use Advance Rest client to send a notification to the device.
Use the link to add extension to chrome
https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
Notification will not receive when app kill, thus you need to Register Receiver to get Notification
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent("com.android.pushnotify.MyFirebaseMessagingService");
i.setClass(context, MyFirebaseMessagingService.class);
context.startService(i);
}
}
add inside Manifest.xml(Application tag)
<receiver android:name="com.androidbash.androidbashfirebasepushnotify.OnBootBroadcastReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Firebase shows two notifications on Android

I am struggling to find the cause for the duplicate notification message on android using Firebase, Unity and sending from nodejs with the help of node-gcm.
Here is all relative code:
Unity3d client side I got:
public class PushServiceManager : MonoBehaviour
{
public string Identifier;
public string SkuId;
public SQSParameters sqsOptions;
private SQSManager sqs;
// Use this for initialization
void Start()
{
sqs = new SQSManager(this.sqsOptions);
sqs.Initialize(this.gameObject);
Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
}
public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token)
{
Debug.Log("Received Registration Token: " + token.Token);
RegistrationToken t = new RegistrationToken();
t.id_token = token.Token;
// sends token to node server
sqs.SendRegistrationToken(t);
}
public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e)
{
Debug.Log(e.Message.Data.ToString());
}
}
Nodejs server side:
pushNotification(pushRequest, tokens, callback) {
// This is an array of firebase tokens
let registrationTokens = tokens.map(function (token) {
return token.token;
});
let message = new gcm.Message({
timeToLive: pushRequest.ttl
});
let note = {
title: 'Message title',
icon: 'none',
sound: 'none',
body: 'message text'
};
message.addNotification(note);
let payload = {
data: {foo: "foo"}
}
message.addData(payload);
this.sender.send(message, {registrationTokens}, callback);
}
Result on device is:
Question:
Why do I get the second empty push notification?
Tapping first one opens up a unity game as expected but tapping that empty one does not.
Where am I going wrong with this?
Thank you!
01.31.17 UPDATE:
Shutout to firebase support team for looking into this issue...
I have the same duplicate notifications issue in my project and below is the solution.
Check your generated AndroidManifest.xml by unity build in [Your unity project folder]\Temp\StagingArea
Look for all receivers that have below line:
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
In my case, I have below that added by the Amazon AWS unity plugin
<receiver android:name="com.amazonaws.unity.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.amazonaws.unity" />
</intent-filter>
</receiver>
and below from Firebase plugin
<receiver android:exported="true" android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.bbbbbttttttgggg.sssssstttt" />
</intent-filter>
</receiver>
The duplicated notification is caused by amazon AWS GCMBroadcastReceiver.
There are two options to fix this.
Remove the receiver if you do not need it.
Add android:exported="false" to the receiver.
Example:
<receiver android:exported="false" android:name="com.amazonaws.unity.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.amazonaws.unity" />
</intent-filter>
</receiver>
Remember to make the change in the original AndroidManifest.xml that contains the receiver. Not the one in Temp\StagingArea. It should be one of the AndroidManifest.xml file inside [Your unity project folder]\Assets\Plugins\Android or it sub folder.
I am facing the same problem with firebase. I am using Firebase together with Microsoft Azure Notification Hub. If I send a test message via Microsoft Notification Hub I only get one message and that message is handled by my Push Handler. Otherwise if I send push notifications through firebase console I am getting two message like you(also one is empty). One message is handled by my push service and the second one is somehow handled by "no code"! I cannot find in my code where the push notification send by firebase is handled? There must be a OnReceiveMessage method in the background which handles the notification. For me I come with following solution: I just uncommented my push handler and now I am only getting one notification, but this without sound...somehow I have to override that function and implement sound behaviour. Have you found a solution for that? The empty message is caused by your push handler the second full message is handled in the background by firebase.
I also getting two different types of message in my onReceive() method:
Microsoft: Bundle[{google.sent_time=1484748187461, from=230XXXXXXXXXX, google.message_id=0:1484748187469719%8a1048bff9fd7ecd, message=Test through Microsoft, collapse_key=do_not_collapse}]
Firebase: Bundle[{google.c.a.udt=0, google.sent_time=1484748603664, gcm.notification.e=1, google.c.a.c_id=3001008833206773803, google.c.a.ts=1484748604, gcm.n.e=1, from=230XXXXXXXXXXX, google.message_id=0:1484748603943016%8a1048bf8a1048bf, gcm.notification.body=Test through firebase, google.c.a.e=1, collapse_key=com.sub_zero.ipostcard}]
So the message received through firebase is handled one time in the background somewhere maybe in through the firebase lib and the second time I suppose by your handler. That why you getting two of them...Just uncomment your push handler and test it again.
I found what was cause this issue...
I had AWS module included into the project which had it's own manifest file. In it there was a receiver declaration for "GCMBroadcastReceiver" in combination with service declaration for "GCMIntentService".
Removing those solved the issue

Issue on receiving push notification on the GCM Client

I'm trying to implement push notification using GCM in my Android Application. I created a server to push messages to devices successfully and also created a api to store the device token in the server successfully. Created a client in application mentioned in the link based on the sample project. And also created a function in php to push notification to the App. When I run that function in the server I'm getting response as success. That means the message is sent from gcm to mobile. But the notification is not shown instead I'm getting the following in the log cat.
06-05 14:58:59.172 23693-28001/com.greenboards.base I/dalvikvm﹕ Could not find method android.app.Notification$Builder.setColor, referenced from method com.google.android.gms.gcm.zza.zzv
06-05 14:58:59.172 23693-28001/com.greenboards.base W/dalvikvm﹕ VFY: unable to resolve virtual method 184: Landroid/app/Notification$Builder;.setColor (I)Landroid/app/Notification$Builder;
06-05 14:58:59.173 23693-28001/com.greenboards.base D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0068
06-05 14:58:59.175 23693-28001/com.greenboards.base W/GcmNotification﹕ Failed to show notification: Missing icon
To capture the message I'm using the same listener service which denoted in the example application(I added below for the reference). So I thought the issue in the notification manager. So I commented it out and run the application. But again I'm getting the same response without any notification. I don't know what is the issue.
package com.greenboards.base;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.greenboards.base.R;
import com.google.android.gms.gcm.GcmListenerService;
import com.greenboards.base.SplashScreen;
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
/**
* Called when message is received.
*
* #param from SenderID of the sender.
* #param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* #param message GCM message received.
*/
private void sendNotification(String message) {
/*Intent intent = new Intent(this, SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 *//* Request code *//*, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 *//* ID of notification *//*, notificationBuilder.build());*/
Log.v("notification message",message);
}
}
But whenever the message received from the server the onMessageReceived must be called in the above listener. In the onMessageReceived function there is two logging function to show message and the sender. That is also not executing. That means the function itself is not executing. Below i added the manifest content.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.greenboards.base"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="19" />
<!-- Application Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.greenboards.base.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.greenboards.base.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Application Configuration and Activities -->
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- [START gcm_receiver] -->
<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.greenboards.base" />
</intent-filter>
</receiver>
<!-- [END gcm_receiver] -->
<!-- [START gcm_listener] -->
<service
android:name="com.greenboards.base.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<!-- [END gcm_listener] -->
<!-- [START instanceId_listener] -->
<service
android:name="com.greenboards.base.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<!-- [END instanceId_listener] -->
<service
android:name="com.greenboards.base.RegistrationIntentService"
android:exported="false">
</service>
</application>
</manifest>
Still now I can't able to debug what is the issue. Am I doing anything wrong or am I am missing anything?
According to this link you should have key/value pair of icon.
Check icon parameter of notification payload. It is specified as required.
So, you must include an icon in the JSON.
An example might be
{
"to":
"ci4ZzC4BW....",
"notification": {
"title": "Testing",
"body": "Success",
"icon": "#drawable/myicon"
}
}
myicon is the image named myicon.png in drawable folder in the application.
onMessageReceived is called when a message with data payload is received. When we change notification to data(like below) in the above json the onMessageReceived function will be called.
{
"to":
"ci4ZzC4BW....",
"data": {
"title": "Testing",
"body": "Success",
"icon": "#drawable/myicon"
}
}
I encounter the same problem
look at the info in logcat:
dalvikvm﹕ Could not find method android.app.Notification$Builder.setColor, referenced from method com.google.android.gms.gcm.zza.zzv
dalvikvm﹕ VFY: unable to resolve virtual method 173: Landroid/app/Notification$Builder;.setColor (I)Landroid/app/Notification$Builder;
and reference the API doc:
http://developer.android.com/reference/android/app/Notification.Builder.html
search "setColor" you will find out it added in "API level 21", means this method only works above 5.0(Lollipop)
I tried the structure below test on 2 different OS device, 5.0 & 4.4 respectively, and only work on 5.0
{"to": "/topics/global","data": {"message": "<message>"},"notification": {"icon": "ic_stat_ic_notification","body": "Use Gradle Command","title": "Self test"}}
Note :
i use the JSON test on OS 5.0, notification is shown, but onMessageReceived still not called
Though an old thread, I wanted to add on to this based on some similar issues that I'd faced.
The app has two states: active and inactive.
If the app is active, sending a notification without an icon value (I suspect the key is still required) would still work. Works for me but the key is still in there.
My JSON object looks like this:
.., icon=, sound=default, title=Bruce...
From developer docs:
For an active Android app, notification payloads are passed to
onMessageReceived() under the notification key in the data bundle.
When the app is inactive:
Notifications are delivered to the notification tray when the app is
inactive.
And here is when I hit the Missing icon issue. So a key and value pair is required if the app is inactive.
If the payload is a notification, ensure that it always has the icon key/value pair so that it will work as expected regardless of whether the app is active or inactive.
See here for details
Finally, there should be a clear distinction between what a notification is and what a data is, in the design of the application. I had been using notification for all push messages for my application which I think is not the right way of doing it.

GCM not Working

I am learning GCM(Google cloud Messaging)
I Completed Following steps
1 - Activated and Obtained a Key for browser apps
2 - added following in manifest
Uses permission : com.google.android.c2dm.permission.RECEIVE
Created permission to prevent other Android applications from registering and receiving the Android application's messages
Created a receiver for com.google.android.c2dm.intent.RECEIVE, with the category set as applicationPackage. The receiver should require the com.google.android.c2dm.SEND permission
3 – in receiver
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
GcmMessageHandler it’s a Intend Service to show a notification on receive gcm message.following is onHandleIntent Method in GcmMessageHandler.
#Override
protected void onHandleIntent(Intent intent) {
handler.post(new Runnable() {
#Override
public void run() {
NotificationManager manager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext());
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("GCM Received");
mBuilder.setContentText("GCM Message");
manager.notify(1, mBuilder.build());
}
});
Log.i("app", "Received ");
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
4 - MainActivity-to register and get clint ID, from log cat I copyed that id.
5 - from browser I make post request to https://android.googleapis.com/gcm/send with authorization,content-type,and registration_ids.
Its gets success message.
But my device not showing notification.
Sorry everyone,
Actually my program is correct. I think it’s a problem with my phone.
(I can’t receive messages from Facebook messenger also,)
but Today morning I surprised, I got every messages from my test app(message that I send 2 days ago), Facebook ,etc.
Thank you everyone.
Follow this and this easy tutorial to send and receive push nothification in Android.
And check package naming and AndroidManifest.xml file configured correctly as explained in this example and set receiver like this:
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="your package name here" />
</intent-filter>
</receiver>

Receive a message on a device with GCM

Actually I am working on the notifications for an Android app.
My two main source of information are this tutorial and the android developer web site.
Let me quickly describe my app:
In my app I use web services (WS) which work with POST HTTP request.
For the Notification I use the GCM system.
My app uses the 'POST HTTP' request system above to be register on my server.
Actually my server does exactly the same job as the one in the tutorial (that means to register an account in the database with to two parameters and the register ID of the device, and send a message to the device with GCM)
Actually all of these steps work:
My app receive successfully gets register ID (gcm.register(SENDER_ID); work)
My app get successfully registered on my server
My server receives a successful message when I try to send a message from my device
{"multicast_id" : 6276079906208554309 , "success" : 1 , "failure" : 0 , "canonical_ids" : 0 , "results" : [{"message_id" : "0:1374826298092960%978fee92f9fd7ecd"}]}
The Problem:
I receive nothing on my device
What I did:
I try to do two versions of the application:
First I made an app using a part of the code of the tutorial, but with using the package com.google.android.gms.gcm.GoogleCloudMessaging instead of the com.google.android.gcm which are deprecated (and used in the tutorial), but I was unable to receive a message, so I try a second version …
This time I took the entire tutorial and just change the register function on the server to use mine, but like the first app, I receive nothing on my device. (I did this to try to understand how work the reception but it did not help me, and now I will forget this way)
Where do I need your help:
I need some/more explanation how to receive the message sent by my server.
My main activity uses the code describe on the android developer web site.
I create a broadcast class using the code on the android developer web site.
I don’t create any IntentService or service, maybe it is my error, but according what I read I understood that I don’t need one, like before with the deprecated GCMBaseIntentService
To conclude:
I really will appreciate some help to understand what I need to receive the message on my device, because actually I don’t know where I can found the information I need to be able to use this system.
Thanks.
PS: if you need some part of my code , just ask me.
EDIT
my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.pushnotifications2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.androidhive.pushnotifications2.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.androidhive.pushnotifications2.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Main activity. -->
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<!-- Register Activity -->
<activity
android:name="com.androidhive.pushnotifications2.cop.RegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main Activity -->
<activity
android:name="com.androidhive.pushnotifications2.MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" >
</activity>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.androidhive.pushnotifications2" />
</intent-filter>
</receiver>
</application>
</manifest>
And my GcmBroadcastReceiver (who come from the tutorial)
the WakeLocker is the same as the tutorial too.
package com.androidhive.pushnotifications2;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GcmBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Intent intent) {
///
WakeLocker.acquire(context);
///
System.out.println("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
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());
} else {
sendNotification("Received: " + intent.getExtras().toString());
}
WakeLocker.release();
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.common_signin_btn_icon_focus_light)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}

Categories

Resources