I have written an application, and in this application I can send a notification to users. In the first version, there were no problems. Then I made revisions with the same key, and I began experiencing problems.
Some devices no longer receive any notification, and one of these devices is my device. Later, I discovered that my device and others are no longer accepting any notification from GCM service, even though I put the new version of my app with GCM along with the new key or any app has GCM.
This problem has been reported to me by others who have updated to the new version of my app . But some users who updated the application works with them without any problems. I mean for some users, the app continues to work correctly.
when I run SuperVPN app all notifications delivered !
so two devices connected to same router
first one get notifications normally
other one not receiving without SuperVPN
manifist.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.labyb.englishwordeachday"
android:versionCode="2"
android:versionName="2.0.0" >
<uses-sdk android:minSdkVersion="11" />
<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="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<permission
android:name="com.labyb.englishwordeachday.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.labyb.englishwordeachday.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.labyb.englishwordeachday.WordActivity"
android:label="#string/app_name"
android:parentActivityName=".AllWordsActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.AddsActivity"
android:label="#string/title_activity_adds"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.AllWordsActivity"
android:label="#string/title_activity_list"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.SplashActivity"
android:label="#string/title_activity_splash"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.labyb.englishwordeachday.SearchActivity"
android:label="#string/title_activity_search"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.TranslateActivity"
android:label="#string/title_activity_translate"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.TestActivity"
android:label="#string/title_activity_test_new" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.ReminderActivity"
android:label="#string/title_activity_reminder"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.SetReminderActivity"
android:label="#string/title_activity_set_reminder"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
<receiver android:name="com.labyb.englishwordeachday.MyReceiver" >
<intent-filter>
<action android:name="com.labyb.englishwordeachday.mybroadcast" />
</intent-filter>
</receiver>
<activity
android:name="com.labyb.englishwordeachday.RemindersActivity"
android:label="#string/title_activity_reminders" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.SpeachActivity"
android:label="#string/title_activity_speach"
android:theme="#android:style/Theme.Holo.Light.Dialog" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.LevelsActivity"
android:label="#string/title_activity_levels" >
</activity>
<activity
android:name="com.labyb.englishwordeachday.WebActivity"
android:label="#string/title_activity_web" >
</activity>
<receiver
android:name="com.labyb.englishwordeachday.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.labyb.englishwordeachday" />
</intent-filter>
</receiver>
<service android:name="com.labyb.englishwordeachday.GcmIntentService" />
<receiver android:name=".StartUpBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
</application>
</manifest>
GcmBroadcastReceiver.java
package com.labyb.englishwordeachday;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GcmIntentService.java
package com.labyb.englishwordeachday;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.labyb.englishwordeachday.classes.Adds;
import com.labyb.englishwordeachday.classes.DatabaseHandler;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
DatabaseHandler db;
static int counter = 0;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString(), "Send error: " + extras.toString(), "Send error: " + extras.toString(), "Send error: " + extras.toString(), "Send error: "
+ extras.toString(), "Send error: " + extras.toString(), "Send error: " + extras.toString(), "Send error: " + extras.toString(), "Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString(),
"Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString(),
"Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString(), "Deleted messages on server: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// for (int i = 0; i < 5; i++) {
// Log.i(TAG, "Working... " + (i + 1) + "/5 # " +
// SystemClock.elapsedRealtime());
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// }
// }
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
sendNotification(extras.get("word_id").toString(), extras.get("m1").toString(), extras.get("m2").toString(), extras.get("m3").toString(), extras.get("m4").toString(), extras.get("m5")
.toString(), extras.get("m6").toString(), extras.get("m7").toString(), extras.get("level").toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
long[] vibraPattern = { 500, 500, 500, 500 };
private void sendNotification(String word_id, String m1, String m2, String m3, String m4, String m5, String m6, String m7, String level) {
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (m4.equals("v1")) {
} else if (m1.equals("newadd")) {
Intent myIntent = new Intent(this, AddsActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle("قد يهمك ايضا")
.setStyle(new NotificationCompat.BigTextStyle().bigText(m2)).setAutoCancel(true).setTicker("قد يهمك ايضا").setVibrate(vibraPattern)
.setSound(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.ewed)).setContentText(m2);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
counter = counter + 1;
db = new DatabaseHandler(this);
db.addAdd(new Adds(m3, m2));// /hereeeeeeeeeeeeee
} else {
Intent i = new Intent(this, WordActivity.class);
i.putExtra("id", word_id);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(m1)
.setStyle(new NotificationCompat.BigTextStyle().bigText(m1)).setAutoCancel(true).setTicker("كلمة إنجليزية جديدة").setVibrate(vibraPattern)
.setSound(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.ewed)).setContentText(m2);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
counter = counter + 1;
db = new DatabaseHandler(this);
db.addNewWord(word_id, m1, m2, m3, m4, m5, m6, m7, level);// /hereeeeeeeeeeeeee
}
}
}
Related
I am facing a very strange problem while implementing broadcast receiver in android. Previously my app was working fine, but suddenly it stopped working for certain type of sms. The receiver does not receive anything when a sms received from a server which has single word server name. For example, if a sms is received from server having senders name as BP-SBIISD my receiver works fine but if the senders name is only SBIISD or SBI only than it does not work. What is this new update that I have missed? can any body help please!
My code Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cowboy.smsforwarder">
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<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.SMSForwarder">
<receiver
android:name=".ReceiveSms"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Receiver Code:
Package com.cowboy.smsforwarder;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.auth.api.phone.SmsRetriever;
public class ReceiveSms extends BroadcastReceiver {
private static final String TAG = "New Broadcast Receiver";
public static final String pdu_type = "pdus";
#Override
public void onReceive(Context context, Intent intent) {
// Get the SMS message.
Log.d(TAG,"Control shifted");
// an Intent broadcast.
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Log.d(TAG,"Massage Received ");
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
String msg_from;
String ContactName = null;
if(bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
SmsManager smsManager = SmsManager.getDefault();
//DatabaseHelper db = new DatabaseHelper(context);
for(int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
//Toast.makeText(context,"From:" + msg_from + ",Body: " + msgBody,Toast.LENGTH_SHORT).show();
Log.d("BroadCast Receiver","Contact Name " + ContactName+msgBody);
Toast.makeText(context,"From NEW APP:" + msg_from + ",Body: " + msgBody,Toast.LENGTH_SHORT).show();
//db.getRules(msg_from,msgBody,ContactName);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
In flutter app the receivers for BOOT_COMPLETED and SMS_RECEIVED not work when the real device is restarted but work fine in 'android emulator' and the real device before the restart
permission for RECEIVED_SMS
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
permission for BOOT_COMPLETED
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Class for RECEIVE_SMS is SmsReceiver
Class for BOOT_COMPLETED is BootReceiver
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="ai.torquevision.encredeble"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.BROADCAST_SMS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:usesCleartextTraffic="true"
android:label="encredeble"
android:icon="#drawable/logo">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<activity
android:name="ai.torquevision.encredeble.MainActivity"
android:supportsPictureInPicture="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<receiver android:name=".Utils.BootReceiver" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<receiver android:name=".Utils.SmsReceiver" android:permission="android.permission.RECEIVE_SMS" android:enabled="true" android:exported="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
BootReceiver.kt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import kotlinx.coroutines.delay
import java.lang.Exception
class BootReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("encredeble", "encredeble context: " + context?.toString() + "intent: " + intent?.action);
Log.i("encredeble", "encredeble context: " + context?.toString() + "intent: " + intent?.action);
if(context == null || intent == null){
return;
}
try{
NotificationHandler.notify(context, "Restart action", "action: " + intent?.action);
Log.w("boot_broadcast_poc", "=======================> starting service...")
if(intent.action.equals("android.intent.action.BOOT_COMPLETED") || intent.action.equals("android.intent.action.QUICKBOOT_POWERON") || intent.action.equals("android.intent.action.LOCKED_BOOT_COMPLETED")){
NotificationHandler.notify(context, "Device restarted", "BOOT COMPLETED");
}
}
catch (err: Exception){
NotificationHandler.notify(context, "Restart error", "Error: " + err.message)
}
}
}
SmsReceiver.kt
import ai.torquevision.encredeble.MainActivity
import ai.torquevision.encredeble.R
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Telephony
import androidx.core.app.NotificationCompat
import android.telephony.SmsMessage
import android.util.Log
import androidx.core.app.NotificationManagerCompat
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.embedding.engine.loader.FlutterLoader
import io.flutter.plugin.common.MethodChannel
import org.json.JSONArray
import org.json.JSONObject
class SmsReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("Sms receive", "===================================> SMS Received")
if(intent ==null) {
return
}
if(Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.action)){
var msg = ""
var msgObj: JSONArray = JSONArray()
for (smsMessage in Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
val messageBody = smsMessage.messageBody
Log.d("msg body", "message body: " + messageBody)
msg = msg + messageBody
var map: JSONObject = JSONObject()
if(msgObj.length() == 0){
map.put("body", messageBody)
map.put("originatingAddress", smsMessage.originatingAddress)
map.put("displayOriginatingAddress", smsMessage.displayOriginatingAddress)
map.put("displayMessageBody", smsMessage.displayMessageBody)
msgObj.put(0, map)
} else {
val expMap = msgObj.get(msgObj.length() - 1) as JSONObject
if(expMap["originatingAddress"] == smsMessage.originatingAddress || expMap["displayOriginatingAddress"] == smsMessage.displayOriginatingAddress){
map = expMap
map.put("body", map["body"].toString() + messageBody)
map.put("displayMessageBody", map["displayMessageBody"].toString() + smsMessage.displayMessageBody)
msgObj.put(msgObj.length() - 1, map)
}else{
map.put("body", messageBody)
map.put("originatingAddress", smsMessage.originatingAddress)
map.put("displayOriginatingAddress", smsMessage.displayOriginatingAddress)
map.put("displayMessageBody", smsMessage.displayMessageBody)
msgObj.put(map)
}
}
}
if(context != null){
SmsMethodChannel.invoke(context, msgObj.toString());
}
}
}
}
Am trying to receive incoming SMS on android application but i can't get the coming SMS received, bellow is the code am using.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
in the mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mdb.com.mmbox">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MySMS" android:label="#string/app_name">
</activity>
<receiver android:name=".IncomingSms">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
</application>
</manifest>
I tried to look for some examples online but none of them seems to work for me, Please point me where am getting things wrong.
I will appreciate your contribution, Thanks
declare your permissions out side of your application tag like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mdb.com.mmbox">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MySMS" android:label="#string/app_name">
</activity>
<receiver android:name=".IncomingSms">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
this is the sender code which is used to send message to gcm.
//sJSONObject obj = new JSONObject();
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(120)
.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
System.out.println("regId: " + regId);
Object result = sender.send(message, regId, 5);
if (StringUtils.isEmpty(((Result) result).getErrorCodeName())) {
System.out.println("success");
System.out.println(result.toString());
}
else{
System.out.println(((Result) result).getErrorCodeName());
System.out.println(result.toString());
}
Manifest file:
<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.javapapers.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.javapapers.android.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" />
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".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>
<activity
android:name="com.javapapers.android.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>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.javapapers.android" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService" />
<!-- added by shashank -->
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
CCMBroadcastreciever:
package com.javapapers.android;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("GCMBroadcastReceiver", "OnReceive method");
System.out.println( "Broadcast receiver OnReceive method");
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GCMNotificationIntentService:
package com.javapapers.android;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GCMNotificationIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCMNotificationIntentService";
#Override
protected void onHandleIntent(Intent intent) {
Log.d("GCMNotificationIntentService", "OnHandleIntent method");
System.out.println( "GCMNotificationIntentService OnHandleIntent method");
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
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)) {
for (int i = 0; i < 3; i++) {
Log.i(TAG,
"Working... " + (i + 1) + "/5 # "
+ SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
sendNotification("Message Received from Google GCM Server: "
+ extras.get(Config.MESSAGE_KEY));
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.gcm_cloud)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
}
Output:
success
[ messageId=0:1414564158966354%31e4cc17f9fd7ecd ]
Still i'm not getting push notification on emulator. i have tried it on device as well. same problem occurs there as well.
I had a similar problem. I solved it using the classes in This GitHub example specifically noting the following:
Three 'services' and one 'receiver' together with all the permissions added in the github example.
AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.VIBRATE" />
<permission
android:name="<yourpackagename>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="<yourpackagename>.permission.C2D_MESSAGE" />
<service
android:name=".utility.MyGcmRegistrationIntentService"
android:exported="false" >
</service>
<service
android:name=".utility.MyGcmListenerService"
android:exported="false" >
<intent-filter>
actionandroid:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter</service>
<service
android:name=".utility.MyInstanceIdListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<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" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="<com.example.yourpackagename>" />
</intent-filter>
</receiver>
The Receiver is implemented in the
ActivityMain.java:
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences.getBoolean(SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
} else {
}
}
};
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter("registrationComplete"));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
You can basically use the other files just like they are:
MyGcmListenerService.java - The one where you can customize your notification icon and text.
MyInstanceIDListenerService.java
QuickstartPreferences.java
RegistrationIntentService.java
I solved it but I no longer have the source code..sorry
I don't receive the notifications on my Android device. The messagge was sent successfully to the GCM servers. I tried them all. Can someone help me? This is the code:
GCMIntentService.java
public class GCMIntentService extends IntentService {
static SharedPreferences prefs;
static Editor editor;
Context context;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM Intent Service";
public static final int NOTIFICATION_ID = 1;
public GCMIntentService() {
super(Configuration.SENDER_ID);
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
String msg = intent.getStringExtra("message");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
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());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
//sendNotification("Received: " + extras.toString());
sendNotification(msg);
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
editor.putInt("lastViewVisited", 1).commit();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getText(R.string.app_name).toString())
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(intent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="<MY-PACKAGE>"
android:versionCode="9"
android:versionName="2.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<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"/>
<!-- GCM -->
<permission android:name="<MY-PACKAGE>.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="<MY-PACKAGE>.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- GCM -->
<receiver android:name="<MY-PACKAGE>.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="<MY-PACKAGE>" />
</intent-filter>
</receiver>
<service android:name="<MY-PACKAGE>.GCMIntentService" android:enabled="true" />
<activity
android:name="<MY-PACKAGE>.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="<MY-PACKAGE>.PreferenceFragment"
android:label="Preferenze">
</activity>
</application>
</manifest>
GcmBroadcastReceiver.java
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GCMIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Try:
Check if you are using the browser api key to send the message from web server to android devices.