I have this code. I enter the project key from the Google console as the snederId and get an error:
service not available.
which steps would you recommend for me to double check in setting up the registration key?
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
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.
sendRegistrationIdToBackend();
saveRegIdToDb();
// For this demo: we don't need to send it because the
// device will send
// upstream messages to a server that echo back the message
// using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
// mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
Some basic checks:
Was your project whitelisted by Google?
Do you use the correct sender_id (project number)?
Is network connection up?
Are Google Play Services installed and up to date?
One of the above checks should not be OK.
check sender id, it is project number
and turn on "APIs & auth" -> "Google Cloud Messaging for Android"
Related
I have a board that sends jsons with telemetry to Azure IoT hub (using http). I want to read telemetry data with my android device. I looked some examples of reading messages from IoT hub for android, but I found only how to read them from "Cloud to device feedback" endpoint. So now my application looks like:
Json from the board ----> "Events" endpoint ---> Function application that resending json to "Cloud to device feedback" endpoint
-----> "Cloud to device feedback" endpoint ----> Android device.
I'm a beginner in Azure, so I'm sure that exists smarter way to do that. (Json from the board ----> "Events" endpoint ---> Android device). I did it on my desktop, but looks like android doesn't work with some libraries from desktop project.
Does anybody know how can I do it? (maybe some guides or lessons)
Desktop version
Part of android code:
public void btnReceiveOnClick(View v) throws URISyntaxException, IOException
{
System.out.println("Receiving:");
Button button = (Button) v;
// Comment/uncomment from lines below to use HTTPS or MQTT protocol
//IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
DeviceClient client = new DeviceClient(connString, protocol);
if (protocol == IotHubClientProtocol.MQTT)
{
MessageCallbackMqtt callback = new MessageCallbackMqtt();
Counter counter = new Counter(0);
client.setMessageCallback(callback, counter);
} else
{
MessageCallback callback = new MessageCallback();
Counter counter = new Counter(0);
client.setMessageCallback(callback, counter);
}
try
{
client.open();
} catch (Exception e2)
{
System.out.println("Exception while opening IoTHub connection: " + e2.toString());
}
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
client.closeNow();
try {
....
}catch (JSONException je){
....
}
}
// Our MQTT doesn't support abandon/reject, so we will only display the messaged received
// from IoTHub and return COMPLETE
static class MessageCallbackMqtt implements com.microsoft.azure.sdk.iot.device.MessageCallback
{
public IotHubMessageResult execute(Message msg, Object context)
{
responce = new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET);
Counter counter = (Counter) context;
System.out.println(
"[from MessageCallbackMqtt] Received message " + counter.toString()
+ " with content: " + responce);
counter.increment();
return IotHubMessageResult.COMPLETE;
}
}
static class EventCallback implements IotHubEventCallback
{
public void execute(IotHubStatusCode status, Object context)
{
Integer i = (Integer) context;
System.out.println("[from EventCallback] IoT Hub responded to message " + i.toString()
+ " with status " + status.name());
}
}
static class MessageCallback implements com.microsoft.azure.sdk.iot.device.MessageCallback
{
public IotHubMessageResult execute(Message msg, Object context)
{
Counter counter = (Counter) context;
System.out.println(
"Received message " + counter.toString()
+ " with content: " + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));
int switchVal = counter.get() % 3;
IotHubMessageResult res;
switch (switchVal)
{
case 0:
res = IotHubMessageResult.COMPLETE;
break;
case 1:
res = IotHubMessageResult.ABANDON;
break;
case 2:
res = IotHubMessageResult.REJECT;
break;
default:
// should never happen.
throw new IllegalStateException("Invalid message result specified.");
}
System.out.println("Responding to message " + counter.toString() + " with " + res.name());
counter.increment();
return res;
}
}
You can refer to this document.It shows how to read the telemetry from you IoT Hub with Java.In the ReadDeviceToCloudMessages.java sample, it connects to the service-side Events endpoint on your IoT Hub and receives the device-to-cloud messages.
BTW, you can get the eventHubsCompatibleEndpoint, eventHubsCompatiblePath and iotHubSasKey from Azure Portal simply. The eventHubsCompatibleEndpoint is in this format:
sb://xxxxxxxxxxxxxx.servicebus.windows.net/
This question is Extension of my previous question on this SO question "How to connect XMPP bosh server using java smack library?"
I am using Java as server side language. I have successfully implement xmpp BOSH connection using smach-jbosh thanks to #Deuteu for helping me to achieve this, so far I have modify jbosh's BOSHClient.java file and added two getter method for extracting RID and SID.
Now I have RID and SID on my app server (I am using Apache Tomcat). I need to pass this credential to Strophe (web client) so that it can attach to connection.
Here I have some doubt.
When to disconnect bosh Connection establish from the app server? before passing sid, rid and jid to strophe or after passing sid, rid and jid to strophe?
As per my observation during implementation for the same, I have observed that once bosh connection from the app server has been disconnected, session is expired and SID and RID is no longer useful!!!
I have implemented this logic (Establishing bosh connection and Extracting sid and rid) on a Servlet, here once response has been send from Servlet, Thread will get expired and end BOSH connection will get terminated, so I am not able perform `Attach()` on strophe as session is expired.
Can somebody help me with that problem?
I believe #fpsColton's answer is correct - I'm just added extra info for clarity. As requested on linked thread here is the code changes I made on this - note: I only added the parts where I've labelled "DH"
In BOSHConnection:
// DH: function to preserve current api
public void login(String username, String password, String resource)
throws XMPPException {
login(username, password, resource, false);
}
// DH: Most of this is existing login function, but added prebind parameter
// to allow leaving function after all required pre-bind steps done and before
// presence stanza gets sent (sent from attach in XMPP client)
public void login(String username, String password, String resource, boolean preBind)
throws XMPPException {
if (!isConnected()) {
throw new IllegalStateException("Not connected to server.");
}
if (authenticated) {
throw new IllegalStateException("Already logged in to server.");
}
// Do partial version of nameprep on the username.
username = username.toLowerCase().trim();
String response;
if (config.isSASLAuthenticationEnabled()
&& saslAuthentication.hasNonAnonymousAuthentication()) {
// Authenticate using SASL
if (password != null) {
response = saslAuthentication.authenticate(username, password, resource);
} else {
response = saslAuthentication.authenticate(username, resource, config.getCallbackHandler());
}
} else {
// Authenticate using Non-SASL
response = new NonSASLAuthentication(this).authenticate(username, password, resource);
}
// Indicate that we're now authenticated.
authenticated = true;
anonymous = false;
// DH: Prebind only requires connect and authenticate
if (preBind) {
return;
}
// Set the user.
if (response != null) {
this.user = response;
// Update the serviceName with the one returned by the server
config.setServiceName(StringUtils.parseServer(response));
} else {
this.user = username + "#" + getServiceName();
if (resource != null) {
this.user += "/" + resource;
}
}
// Create the roster if it is not a reconnection.
if (this.roster == null) {
this.roster = new Roster(this);
}
if (config.isRosterLoadedAtLogin()) {
this.roster.reload();
}
// Set presence to online.
if (config.isSendPresence()) {
sendPacket(new Presence(Presence.Type.available));
}
// Stores the autentication for future reconnection
config.setLoginInfo(username, password, resource);
// If debugging is enabled, change the the debug window title to include
// the
// name we are now logged-in as.l
if (config.isDebuggerEnabled() && debugger != null) {
debugger.userHasLogged(user);
}
}
and
// DH
#Override
public void disconnect() {
client.close();
}
then my Client-side (Web Server) wrapper class - for connecting from within JSP is:
Note: This is proving code rather than production - so there's some stuff in here you may not want.
public class SmackBoshConnector {
private String sessionID = null;
private String authID = null;
private Long requestID = 0L;
private String packetID = null;
private boolean connected = false;
public boolean connect(String userName, String password, String host, int port, final String xmppService) {
boolean success = false;
try {
Enumeration<SaslClientFactory> saslFacts = Sasl.getSaslClientFactories();
if (!saslFacts.hasMoreElements()) {
System.out.println("Sasl Provider not pre-loaded");
int added = Security.addProvider(new com.sun.security.sasl.Provider());
if (added == -1) {
System.out.println("Sasl Provider could not be loaded");
System.exit(added);
}
else {
System.out.println("Sasl Provider added");
}
}
BOSHConfiguration config = new BOSHConfiguration(false, host, port, "/http-bind/", xmppService);
BOSHConnection connection = new BOSHConnection(config);
PacketListener sndListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
SmackBoshConnector.this.packetID = packet.getPacketID();
System.out.println("Send PacketId["+packetID+"] to["+packet.toXML()+"]");
}
};
PacketListener rcvListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
SmackBoshConnector.this.packetID = packet.getPacketID();
System.out.println("Rcvd PacketId["+packetID+"] to["+packet.toXML()+"]");
}
};
PacketFilter packetFilter = new PacketFilter() {
#Override
public boolean accept(Packet packet) {
return true;
}
};
connection.addPacketSendingListener(sndListener, packetFilter);
connection.addPacketListener(rcvListener, packetFilter);
connection.connect();
// login with pre-bind only
connection.login(userName, password, "", true);
authID = connection.getConnectionID();
BOSHClient client = connection.getClient();
sessionID = client.getSid();
requestID = client.getRid();
System.out.println("Connected ["+authID+"] sid["+sessionID+"] rid["+requestID+"]");
success = true;
connected = true;
try {
Thread.yield();
Thread.sleep(500);
}
catch (InterruptedException e) {
// Ignore
}
finally {
connection.disconnect();
}
} catch (XMPPException ex) {
Logger.getLogger(SmackBoshConnector.class.getName()).log(Level.SEVERE, null, ex);
}
return success;
}
public boolean isConnected() {
return connected;
}
public String getSessionID() {
return sessionID;
}
public String getAuthID() {
return authID;
}
public String getRequestIDAsString() {
return Long.toString(requestID);
}
public String getNextRequestIDAsString() {
return Long.toString(requestID+1);
}
public static void main(String[] args) {
SmackBoshConnector bc = new SmackBoshConnector();
bc.connect("dazed", "i3ji44mj7k2qt14djct0t5o709", "192.168.2.15", 5280, "my.xmppservice.com");
}
}
I confess that I'm don't fully remember why I put the Thread.yield and Thread.sleep(1/2 sec) in here - I think - as you can see with added PacketListener - the lower level functions return after sending data and before getting a response back from the server - and if you disconnect before the server has sent it's response then it (also) causes it to clean up the session and things won't work. However it may be that, as #fpsColton says, this dicsonnect() isn't actually required.
Edit: I now remember a bit more about whay I included sleep() and yield(). I noticed that Smack library includes sleep() in several places, including XMPPConnection.shutdown() as per source. Plus in terms of yield() I had problems in my environment (Java in Oracle Database - probably untypical) when it wasn't included - as per Smack Forum Thread.
Good luck.
After you have created a BOSH session with smack and have extracted the SID+RID values, you need to pass them to Strophe's attach() and from here on out you need to let strophe deal with this connection. Once Strophe has attached, you do not want your server to be doing anything to the connection at all.
If your server side code sends any messages at all to the connection manager after strophe has attached, it's likely that it will send a invalid RID which will cause your session to terminate.
Again, once the session has been established and is usable by strophe, do not attempt to continue using it from the server side. After your server side bosh client completes authentication and you've passed the SID+RID to the page, just destroy the server side connection object, don't attempt to disconnect or anything as this will end your session.
The thing you need to remember is, unlike traditional XMPP connections over TCP, BOSH clients do NOT maintain a persistent connection to the server (this is why we use BOSH in web applications). So there is nothing to disconnect. The persistent connection is actually between the XMPP server and the BOSH connection manager, it's not something you need to deal with. So when you call disconnect from your server side BOSH client, you're telling the connection manager to end the session and close it's connection to the XMPP server, which completely defeats the purpose of creating the session in the first place.
I am trying to set up GCM but my project doesn't recognize certain methods. I followed the advice of many other links which was to import GCM and google play services but I am still getting no such luck. Thanks for looking.
Edit: I've cleaned a million times and rebuilt.
I'm not sure where you got the code of the demo app from, but there are several things wrong with it.
First of all, the method you are missing is not implemented in the Demo. It has an empty body :
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
It's your responsibility to implement it, since its implementation depends on your server implementation.
Another error (you'd get an exception after you fix the compilation error) is calling gcm.register() from the main thread. You must call it in the background :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
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.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
All code samples are taken from the official GCM Demo app.
I am using GCM. Its work perfect but after unregister i still receive notifications.
This is my registration:
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
Toast.makeText(context, "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, user, pass, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}`
And from different activity i am trying to unregister from GCM:
GCMRegistrar.unregister(getApplicationContext());
GCMRegistrar.onDestroy(getApplicationContext());
And after that i still receive notifications :(
First, GCMRegistrar is deprecated.
Second, unregister() indicates that this device should never again receive messages. Frequently registering and unregistering is not expected app behavior. If you want to stop receiving messages, tell your app server to stop sending them.
My aplication is a multiplayer game in android, with a server running on google app engine and using GCM to conect the server with the player devices. i have registered the device in GCM and then i sent the registerId to the server to connect with the device. When i run the game sometimes it works fine but sometimes the device doesn¡t receive anything from GCM, the server still receive from the device. I have no idea what is happening :s
Here is where i register my device in the onCreate of the main class :
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
if (GCMRegistrar.isRegistered(this)) {
Log.d("info", GCMRegistrar.getRegistrationId(this));
}
regId = GCMRegistrar.getRegistrationId(this);
deviceId = getDeviceId();
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
Log.d("info", GCMRegistrar.getRegistrationId(this));
}
Then the first time i run the application on a phone i use this code to send the registationId to the server:
sendMessage("code=" + REGISTRATION_CODE +
"&deviceId=" + deviceId +
"®Id=" + regId +
"&phoneNumber=" + phoneNumber);
And here is the code in the server to send messages back to the device:
public void sendMessage(String regId, String text) {
Sender sender = new Sender(APIKey);
Message message = new Message.Builder().collapseKey("1").timeToLive(3).delayWhileIdle(true).addData("message", text).build();
try {
sender.send(message,regId,1);
} catch (IOException e) {
e.printStackTrace();//Manejar la excepcion
}
}
I can't understand why stop working, i'm in the middle of a game and stops working and then works again ...
I just solved it, the problem was the collapseKey here
Message message = new Message.Builder().collapseKey("1").timeToLive(3).delayWhileIdle(true).addData("message", text).build();
If you use the same collapseKey always sometimes you don't receive messages randomly so i try this and works finally works!!
Message message = new Message.Builder().collapseKey(""+((int) (Math.random () * (10000)))).timeToLive(3).delayWhileIdle(true).addData("message", text).build();