i've followed google instruction on initiating a gcm server and client.
my problem is though i get a successful gcm from server :
MulticastResult(multicast_id=8287827393174436535,total=1,success=1,failure=0,canonical_ids=0,results:
[[ messageId=0:1366468335181772%8e1522ac00000031 ]]
i'm not able to see any movement of receiving a message on the client - onMessage() isn't called.
client id as well as server id are correct as far as i can tell.
i'd appreciate any help... :)
the server side code :
try {
Sender sender = new Sender(API_KEY);
Message message = new Message.Builder().collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message",
"this text will be seen in notification bar!!").build();
ArrayList<String> devices = new ArrayList<String>();
devices.add(DEVICE_ID1);
//devices.add(DEVICE_ID2);
MulticastResult result = sender.send(message, devices, 2);
//Result result = sender.send(message, DEVICE_ID1, 2);
System.out.println(result.toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println(error);
}
} catch (Exception e) {
// TODO: handle exception
}
the client code :
registering :
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID); // Note: get the sender id from configuration.
String regIdString = GCMRegistrar.getRegistrationId(this);
Log.v(TAG, "RegisterId, regId: " + regIdString);
} else {
Log.v(TAG, "Already registered, regId: " + regId);
}
and gcmIntentServiceCreated (partly) :
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService(){
super(SENDER_ID);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("Registration", "Got a message!");
Log.i("Registration", context.toString() + " " + intent.toString());
}
...
}
client's manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission android:protectionLevel="signature" android:name="com.example.myapp.permission.C2D_MESSAGE"></permission>
<uses-permission android:name="com.example.myapp.permission.C2D_MESSAGE"/>
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.google.android.gcm.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.example.myapp" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
To maximise your chances of receiving the message, I would not set the time_to_live at a mere 3 seconds. I'd omit this parameter altogether so that it takes the default value of 4 weeks. I would also set delay_while to false, so that the phone gets the message even whilst idle.
Well your message is surely getting sent to your device since gcm sends a success status of 1. Try to check the GCMReceiver code of your app.
Change the following code in your onMessage method:
Log.i("Registration", "Got a message!");
Log.i("Registration", context.toString() + " " + intent.toString());
to this:
String message=intent.getStringExtra("message");
Log.w("The message received is", message);
hope this help
Related
How can I detect a mounted device such as a Pen-Drive, that can be used for storage? How can I find the path for the mounted storage device so I may read files from it?
I've used following broadcast receiver taking the permission to access mounted device:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
Log.d(TAG, "onReceive: "+intent.getExtras().toString());
Log.d(TAG, "onReceive: "+intent.getData());
LinearLayout layoutUsbList = (LinearLayout)findViewById(R.id.layout_usb_list);
Button btn = new Button(MainActivity.this);
btn.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layoutUsbList.addView(btn);
btn.setText(device.getDeviceId()+"\t"+device.getDeviceName());
Log.d(TAG, "onReceive: "+intent.getExtras().toString());
final String path = intent.getData().getPath();
Log.e(TAG, "onReceive: path of device received from intent: "+ path );
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(path);
Toast.makeText(MainActivity.this, "file exists --> "+file.exists()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "file is directory --> "+file.isDirectory()+"", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: file is directory --> "+file.isDirectory()+"");
try{
Toast.makeText(MainActivity.this, file.listFiles().length+"", Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(MainActivity.this, "error while showing total items", Toast.LENGTH_SHORT).show();
}
}
});
}
} else {
Log.d("ERROR", "permission denied for device " + device);
}
}
}
}
};
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.usb.host"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="keyboard|orientation"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter"/>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
</intent-filter>
<!---->
<!---->
<!---->
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED"/>
<data android:scheme="file"/>
</intent-filter>
</activity>
</application>
Accordig to this pdf refrencing this library.
Every mass storage device has at least one interface descriptor with the class code 08h,
which stands for the mass storage class. The mass storage class is not defined in the device
descriptor! The USB interface has exactly two endpoint descriptors. One IN endpoint to
read from the device and one OUT endpoint to write to the device2. Reading and writing
in this case does not necessarily mean reading or writing on the actual storage medium,
this is described later.
There are two different types regarding the mass storage class. There is the bulk-only
transport (BBB) mechanism which is the most common one. All newer devices follow that
standard. Then there is the Control/Bulk/Interrupt (CBI) standard which is no longer
important, because the USB-IF recommends using the BBB approach
UsbDevice is recognized as massStorage Device If:
usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE
|| usbInterface.getInterfaceSubclass() == INTERFACE_SUBCLASS // int 6
|| usbInterface.getInterfaceProtocol() == INTERFACE_PROTOCOL // int 80
and
usbInterface.getEndpointCount() == 2
where
one of endpoint must satisfy following:
endPoint direction == 0
endPoint type = UsbConstants.USB_ENDPOINT_XFER_BULK //int 2
I click on send button in my app and emulator craches with following error message :
HAX is working and emulator runs in fast virt mode
dyld: lazy symbol binding failed: Symbol not found: _utf8_write
Referenced from: /Users/Nabil/Documents/Development/Android/sdk/tools/emulator64-x86
Expected in: flat namespace
dyld: Symbol not found: _utf8_write
Referenced from: /Users/Nabil/Documents/Development/Android/sdk/tools/emulator64-x86
Expected in: flat namespace
Here is my class code :
public void Send (View view){
txtnum = (EditText)findViewById(R.id.txtNum);
txtmsg = (EditText)findViewById(R.id.txtMessage);
String phoneNo = txtnum.getText().toString();
String message = txtmsg.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
and my manifest file:
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
First know android simulators are not real devices. Use any real devices, because real devices only interact with hardware config(Sim Card).
Before you point this as a duplicate, I know this has been asked many a times but it seems after the launch of new GCM (that which requires one to include play services project as library) things have changed on how to correctly implement gcm in our code.
The breakpoint in my GCMIntentService.java and GcmBroadcastReceiver.java gets hit on register since I have set <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> in the manifest but the breakpoints don't get hit when i send a push from the server. Here's all which you would ever need:
Relevant AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aceast.waveindia"
android:versionCode="1"
android:versionName="waveindia1" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="11" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission
android:name="com.aceast.waveindia.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver
android:name=".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.aceast.waveindia" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
GCMBroadcastReceiver.java
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
//breakpoint gets hit on register here...
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);
}
}
Part of GCMIntentService which breakpoint hits on register
#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);
.NET code which triggers push
public string SendNotification()
{
var value = Message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
// tRequest.ContentType = " application/json;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GOOGLE_APPID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + DeviceID + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
Local firewall has 5228-5230 ports unblocked
Now can you point the error?
I see a problem in your manifest :
<uses-permission
android:name="com.aceast.waveindia.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
Should be :
<permission android:name="com.aceast.waveindia.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.aceast.waveindia.permission.C2D_MESSAGE" />
I wrote send and received sms in android... I checked received phone number with special number(a phone number that received sms just it) in onReceive method, but this program opened for every phone number that sent sms!!!! but I dont want it!!!!!! my question is that broadcast receiver class for every received sms from every phone number that opened and automatically running?
public class SmsReceiver extends BroadcastReceiver {
public String str = "";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
//for get sms from special number===============================
String msg_from = msgs[i].getOriginatingAddress();
Log.v("msg_from >>",msg_from);
if(msg_from.equals("08522215"))
{
//===============================
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
}
// ---display the new SMS message---
// Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message", str);
context.startActivity(act);
}
abortBroadcast();
}
}
manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<activity android:name=".SMS"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"
android:label="#string/app_name"/>
<receiver
android:name="com.example.sms.SmsReceiver"
class="com.example.sms.SmsReceiver" >
<intent-filter android:priority="100" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
I think it's because you use this code:
if(msg_from.equals("08522215"))
You should set your number completely (0098913...) or perhaps you can use this code
if(msg_from.contain("08522215")
the following program is my sample program for Listening incoming sms.It is created .apk file
with out error but it does not display the message please help me.the toast does not display
any message if the emulator receive the message.
My scenario is receive the sms ansd display the alert dialog box to user.that sms contanins
email address depending on that address my app search the phone contacts and send the contact
number of the emailId's person as reply message
public void onReceive(Context context,Intent intent)
{
Bundle extras=intent.getExtras();
String messages="";
if(extras!=null)
{
Object[] smsExtra=(Object[]) extras.get("pdus");
for(int i=0;i<smsExtra.length;i++)
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
}
Toast.makeText(context, messages, Toast.LENGTH_SHORT).show(); // not display
}
}//onReceive
my manifastfile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="e.x.x"
android:versionCode="1"
android:versionName="0.1" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<receiver android:name=".ex2" android:exported="true" >
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</manifest>
I'm not sure about manifest. Try like in this example Android – Listen For Incoming SMS Messages
I think android:priority="999" and android:exported="true" is a root of problem