I tried to register my device into GCM service.
that's worked, I get register id of my device and store that on my server.
but when I send message to my device nothing affected and device can not recive message.
Response on google at send message:
{u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8319562714448073760L, u'results': [{u'message_id': u'0:1445751667241995%f044e3acf9fd7ecd'}]}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.ac.buqaen.rc"
android:versionCode="5"
android:versionName="1.4">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.VIBRATE"/>
<permission
android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:name=".network.AppController"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:theme="#style/Theme.Main"
android:allowBackup="true">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".gcm.MessageActivity"/>
<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="ir.ac.buqaen.rc" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
ServerUtilities.java
public final class ServerUtilities {
private static final String TAG = "GCM";
public static void register(final Context context, final String regId){
final MySharedPreferences sp = new MySharedPreferences(context);
long teacher_id = sp.sharedPreferences.getLong("teacher_id", -1);
TeacherHelper teacherHelper = new TeacherHelper(context);
teacherHelper.teacher = teacherHelper.findById(teacher_id);
Map<String, String> params = new HashMap<String, String>();
Log.d("regid", "---- regId:" + regId);
params.put("reg_id", regId);
params.put("name", teacherHelper.teacher.getStringName());
params.put("email", teacherHelper.teacher.getStringEmail());
params.put("user_id", teacherHelper.teacher.getStringUsername());
params.put("device_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
CustomRequest request = new CustomRequest(context, Globals.UrlGCMRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
try {
int vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
if (data.getBoolean("status")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
sp.saveToPreferences("gcm_reg_id", regId);
GCMRegistrar.setRegisteredOnServer(context, true);
} else if (data.getString("msg").equals("already registered")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
GCMRegistrar.setRegisteredOnServer(context, true);
sp.saveToPreferences("gcm_reg_id", regId);
} else {
Log.e(TAG, "registering device failed");
}
} catch (JSONException e) {
Log.e("Response Error _ " + context.getClass().getSimpleName(), "----" + e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
/**
* Unregister this account/device pair within the server.
*/
public static void unregister(final Context context, final String regId) {
final MySharedPreferences sp = new MySharedPreferences(context);
Map<String, String> params = new HashMap<String, String>();
params.put("reg_id", regId);
CustomRequest request = new CustomRequest(context, Globals.UrlGCMUnRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
if (data.getBoolean("status")) {
int vc = 1;
try {
vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
sp.editor.remove("gcm" + vc);
sp.editor.remove("gcm_reg_id");
sp.editor.commit();
GCMRegistrar.setRegisteredOnServer(context, false);
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(Globals.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
ServerUtilities.register(context, registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
ServerUtilities.unregister(context, registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("tes", "~~~" + intent.getExtras());
Log.i(TAG, "Received message");
MessageHelper messageHelper = new MessageHelper(context);
try {
JSONObject data = new JSONObject(intent.getExtras().getString("message"));
messageHelper.message = new Message(
null, data.getInt("type"), data.getInt("status"), data.getString("content"),
data.getString("title"), data.getString("date")
);
messageHelper.Save();
createNotification(context, messageHelper.message);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
private void createNotification(Context context, Message message) {
Intent notificationIntent;
notificationIntent = new Intent(this, Message.class);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationIntent.putExtra("message_id", message.id);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, message.id.intValue(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.bu_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bu_logo))
.setTicker(getString(R.string.new_message))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://ir.ac.buqaen.rc/raw/notification"))
.setContentTitle(message.title)
.setContentText(message.getContentText(context));
Notification notification = builder.build();
notificationManager.notify(message.id.intValue(), notification);
}
}
MainActivity
try {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getApplicationContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getApplicationContext());
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(getApplicationContext());
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(getApplicationContext(), Globals.SENDER_ID);
} else {
// Try to register again if device is not registered on GCM
if (!GCMRegistrar.isRegisteredOnServer(getApplicationContext())) {
ServerUtilities.register(getApplicationContext(), regId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I dont khow why this code not worked! I use this code in another project and get messages on my app, but this code in this application on receive messages.
Can problem from my package name? :)
ir.ac.buqaen.rc
Please help me hoe to fix this problem.
According to Set up a GCM Client App on Android
For existing apps that extend a WakefulBroadcastReceiver, Google
recommends migrating to GCMReceiver and GcmListenerService. To
migrate:
In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current
service declaration that extends IntentService to the new
GcmListenerService
Remove the BroadcastReceiver implementation from your client code
Refactor the current IntentService service implementation to use GcmListenerService
Then, you can refer to my following manifest file. Hope this helps!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gcmclient" >
<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.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service android:name=".service.GcmService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".service.LoggingService" android:exported="false" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:clearTaskOnLaunch="false"
android:finishOnTaskLaunch="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I can't seem to get a basic sms reading app to work on android. Not sure what am I missing here. I think I have all the basic minimum specified in the code, despite that it seems to be not working. The onReceive() of SmsReceiver is never invoked. All the required permissions are set.
Here are my files.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//...
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestReadAndSendSmsPermission();
smsReceiver = new SmsReceiver() {
#Override
protected void onData(String data) {
//handle
}
};
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
//intentFilter.setPriority(999);
registerReceiver(smsReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
}
private void requestReadAndSendSmsPermission() {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS},1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECEIVE_SMS},1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_RESPOND_VIA_MESSAGE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CHANGE_NETWORK_STATE}, 1);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET}, 1);
}
//...
//...
}
SmsReceiver.java
public abstract class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if (context == null || intent == null) {
return;
}
String action = intent.getAction();
if (!action.equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
return;
}
//read sms
onData("sms received");
}
protected abstract void onData(String data);
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysmsapp">
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_RESPOND_VIA_MESSAGE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MySMSApp">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You are missing defining the receiver entry in AndroidManifest.xml file for your BroadcastReceiver named SmsReceiver please make the entry for it else OS will not know if you have a broadcast receiver waiting to be triggered.
Depending upon what is your use case it might be something like
<receiver
android:name=".SmsReceiver"
android:exported="true"
android:permission="com.google.android.gms.auth.api.phone.permission.SEND">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
Or
<receiver
android:name=". SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Note: These receiver are sample receiver please use the correct one as per your use case, the main point is you are missing receiver entry in your manifest file
i use this code to read incoming message
public class SmsReceiver extends BroadcastReceiver {
private static final Uri smsuri = Apconsts.smsuri;
private static final String pdu_type = "pdus";
#Override
public void onReceive(Context context, Intent intent){
// Get the SMS message.
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String format = bundle.getString("format");
// Retrieve the SMS message received.
Object[] pdus = (Object[]) bundle.get(pdu_type);
String body="";String adrs="";
if (pdus != null) {
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++){
if(Build.VERSION.SDK_INT < 23){ msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); }
else{ msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format); }
adrs=msgs[i].getOriginatingAddress();
body += ""+msgs[i].getMessageBody();
}
Toast.makeText(getApplicationContext(), "The message Body: "+body+"\nThe address: "+adrs, Toast.LENGTH_LONG).show();
}
}
}
and this receiver in manifest
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
I have looked at several questions on this site and none seem to be able to answer my question so hopefully someone can help with this. Currently for some reason when I send a message through from the PHP Website, my app doesn't receive the message. I have tried placing Log.d's in the lines of code but it doesn't appear as well. Can someone help to see if something has gone wrong?
[UPDATE] This is the result when I send from the php website
{"multicast_id":5610818169388245295,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1460536959734990%40ad5721f9fd7ecd"}]}
My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.amosang.pushtest" >
<!-- GCM Permissions - Start here -->
<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.example.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
</application>
<receiver
android:name=".GCMBroadcastReceiver"
android:enabled="true"
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.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService">
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</service>
</manifest>
My Broadcast Receiver
public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
Log.d("TESTTEST", "TEST");
setResultCode(Activity.RESULT_OK);
}
}
My intent service
public class GCMNotificationIntentService extends IntentService{
//set ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GCM Intent Service");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
Log.d("RECEIVEDMESSAGE", messageType);
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("Message Received from Google GCM Server:nn"
+ extras.get(AppConstants.MSG_KEY));
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg){
Intent resultIntent = new Intent(this, HomeActivity.class);
Log.d("RECEIVEDPT2",msg);
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("Alert")
.setContentTitle("You've received a new message");
//Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//Set vibration
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 notifications");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
Please help.
Hello I am working with parse push notification for android.I developed app using the following tutorial. http://www.androidhive.info/2015/06/android-push-notifications-using-parse-com/. I can able to get the notification onl in one device which is lollipop.I didin't get notification in kitkat and other devices. I didin't find the issue.
here is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_new_user.testnotification" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.example.android_new_user.testnotification.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.android_new_user.testnotification.permission.C2D_MESSAGE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.android_new_user.testnotification.LoginActivity"
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="com.example.android_new_user.testnotification.MainActivity"
android:label="#string/app_name" />
<service android:name="com.parse.PushService" />
<receiver
android:name=".CustomPushReciver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
</application>
</manifest>
and my reciver File is looks like
package com.example.android_new_user.testnotification;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.parse.ParsePushBroadcastReceiver;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Android_new_user on 11/25/2015.
*/
public class CustomPushReciver extends ParsePushBroadcastReceiver {
private final String TAG = CustomPushReciver.class.getSimpleName();
private NotificationUtils notificationUtils;
private Intent parseIntent;
public CustomPushReciver() {
super();
}
#Override
protected void onPushReceive(Context context, Intent intent) {
super.onPushReceive(context, intent);
if (intent == null)
return;
try {
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
Log.e(TAG, "Push received: " + json);
parseIntent = intent;
parsePushJson(context, json);
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
#Override
protected void onPushDismiss(Context context, Intent intent) {
super.onPushDismiss(context, intent);
}
#Override
protected void onPushOpen(Context context, Intent intent) {
super.onPushOpen(context, intent);
}
/**
* Parses the push notification json
*
* #param context
* #param json
*/
private void parsePushJson(Context context, JSONObject json) {
try {
boolean isBackground = json.getBoolean("is_background");
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
if (!isBackground) {
Intent resultIntent = new Intent(context, MainActivity.class);
showNotificationMessage(context, title, message, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
private void showNotificationMessage(Context context, String title, String message, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.putExtras(parseIntent.getExtras());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, intent);
}
}
and my Application class
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
// register with parse
ParseUtils.registerParse(this);
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
}
How can I resolve this problem. Please help Thanks in adavance
Have you added the application name to your manifest file?
And also check the following code in the manifest
<permission
android:name="yourpackagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="yourpackagename.permission.C2D_MESSAGE" />
<receiver
android:name="com.parse.ParsePushBroadcastReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.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="yourpackagename" />
</intent-filter>
</receiver>
I follow the example of http://hmkcode.com/android-google-cloud-messaging-tutorial/ , every thing is fine but its alway response SERVICE_NOT_AVALIBLE
The device time is correctly setup, package name is correct,too.
could anyone help me in this case
my MainActivity.java
Button btnRegId;
EditText etRegId;
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = "943411953393";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegId = (Button) findViewById(R.id.btnGetRegId);
etRegId = (EditText) findViewById(R.id.etRegId);
btnRegId.setOnClickListener(this);
}
public void getRegId(){
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
etRegId.setText(msg + "\n");
}
}.execute(null, null, null);
}
#Override
public void onClick(View v) {
getRegId();
}
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gmc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<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.example.gmc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gmc.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/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>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gmc" />
</intent-filter>
</receiver>
<service android:name=".GcmMessageHandler" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
try this
#Override
protected String doInBackground(Void... params) {
String msg = "";
int backoff = 2000;
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
}
catch (IOException ex) {
ex.printStackTrace()
}
for(int i=0;i<5;i++){
try {
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
break;
}
catch (IOException ex) {
msg = "Error :" + ex.getMessage();
backoff =backoff * 2;
Thread.sleep(backoff);
}
}
return msg;
}
you need to try several attempts increasing the wait time for each try.
I have a problem with the GCM service.
My app correctly work on android >= 4.0 device but not (e.g) on gingerbread.
I think that the problem it's the manifest but seem right
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<permission android:name="com.example.maptest.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.maptest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 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" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library android:name="com.google.android.maps"/>
<activity
android:name=".RegisterActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.maptest.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="MapTest" />
</intent-filter>
</receiver>
<service android:name="com.example.maptest.GCMIntentService" android:enabled="true"/>
</application>
</manifest>
And my class
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
Log.d(TAG,"CREATO IL Servizio");
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
/*TODO*/
MainActivity.regId=registrationId;
}
/**
* Method called on device un registred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
}
In the LogCat nothing it's displayed.
Can someone help me ?
Thank's!
If this is com.example.maptest your package name, it should be the one that you declare in your manifest file in
<category android:name="MapTest" />
to be something like this
<category android:name="com.example.maptest" />