Android GCM - not getting registration token - android

I am implementing GCM. I have registered my application on Google developer Console, enabled the GCM API services, place google-services.json in app folder, put following in manifest :
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="<my-package-name>.permission.C2D_MESSAGE" />
<application>..
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- GCM -->
<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" />
<action android:name="android.net.conn." />
<category android:name="<my-pakage-name>" />
</intent-filter>
</receiver>
<service
android:name=".notifications.GCMListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".notifications.InstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name=".notifications.RegistrationIntentService"
android:exported="false"></service>
</application>
App level build.gradle
apply plugin: 'com.google.gms.google-services'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.google.android.gms:play-services-gcm:8.1.0'
}
project level build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.google.gms:google-services:1.4.0-beta3'
}
Therefore my query is, I don't know what is wrong with above that I amot getting registration token. Please help me to get registration token

You need to create your own Receiver and Service and use it like this.
Receiver:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class GCMMessageReciever 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);
}
}
Service:
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import com.appdupe.uberforxserviceprovider.R;
import com.google.android.gcm.GCMBaseIntentService;
import com.uber.driver.MyMainFragmentActivity;
import com.uber.driver.constants.Constants;
import com.uber.driver.gcm.ServerUtilities;
import com.uber.driver.util.Utils;
public class GCMIntentService extends GCMBaseIntentService {
private NotificationManager mNotificationManager;
public GCMIntentService() {
super(Constants.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
Intent i = new Intent(Constants.PUSHNOTIFICATION);
i.putExtra(Constants.DB_PHONE_GCM_ID, registrationId);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
ServerUtilities.register(context, "name", "email", registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
String jsonString = intent.getExtras().getString("message");
try {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Editor editor = preferences.edit();
JSONObject jsonObject = new JSONObject(jsonString);
if (jsonObject.getString("id").equals("1")) {
editor.putFloat(Constants.USER_LATTITUDE,
Float.parseFloat(jsonObject.getString("lattitude")));
editor.putFloat(Constants.USER_LOGITUDE,
Float.parseFloat(jsonObject.getString("logitude")));
editor.putString(Constants.USER_RANDOM_ID,
jsonObject.getString("random_id"));
editor.putBoolean(Constants.IS_USER_SET, true);
editor.putString(Constants.PHONE_CLIENT,
jsonObject.getString("client_contact"));
editor.putString(Constants.PHONE_OPEARTOR,
jsonObject.getString("operator_contact"));
// editor.putBoolean(Constants.IS_USER_SET, true);
editor.putString(Constants.CLIENT_NAME,
jsonObject.getString("client_name"));
sendNotification(jsonString);
} else {
editor.putBoolean(Constants.DB_IS_JOB_DONE, true);
editor.putInt(Constants.FRAGMENT_POSITION,
Constants.FRAGMENT_MAP);
editor.putString(Constants.USER_RANDOM_ID, "");
}
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Utils.log("Received message.. " + jsonString);
Intent i = new Intent(Constants.PUSHNOTIFICATION);
i.putExtra("json", jsonString);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
#Override
protected void onDeletedMessages(Context context, int total) {
}
#Override
public void onError(Context context, String errorId) {
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
#Override
protected void onUnregistered(Context arg0, String arg1) {
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MyMainFragmentActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(
getResources().getString(R.string.text_uber_driver))
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText(getResources().getString(
R.string.text_job_assigned)))
.setDefaults(
Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager
.notify(Constants.NOTIFICATION_ID, mBuilder.build());
}
}
Android manifest:
<application>..
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- GCM -->
<receiver
android:name=".GCMMessageReciever"
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" />
<action android:name="android.net.conn." />
<category android:name="<my-pakage-name>" />
</intent-filter>
</receiver>
<service
android:name=".GCMIntentService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".notifications.InstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name=".notifications.RegistrationIntentService"
android:exported="false"></service>
</application>

Related

How to create a notification at a specific time in the future? (Android)

Right now I want to choose a specific time and send a notification to the user, but the app only sends a notification when running in the background. How can I send a notification when the application is completely closed?
This is my MainActivity.java class
package com.vortex.notification;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNotificationChannel();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,4);
calendar.set(Calendar.MINUTE,48);
calendar.set(Calendar.SECOND,3);
Intent intent = new Intent(getApplicationContext(),Notification_reciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
});
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "LemubitReminderChanel";
String description = "Chanel for Lemubit Reminder";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("notifyLemubit", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
This is my Notification_reciver.java class
package com.vortex.notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
public class Notification_reciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repating_intent = new Intent(context,Repating_activity.class);
repating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"notifyLemubit")
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("Bildirim Başlığı")
.setContentText("Bildirim Yazısı")
.setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
And this my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vortex.notification">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Notification_reciver" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>
</application>
</manifest>
I had same issue and I solved it by changing this line
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
To this:
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,0);
And in manifest change your receiver from this
<receiver android:name=".Notification_reciver" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>
To this:
<receiver android:name=".Notification_reciver"
android:enabled="true"
android:exported="true"
android:process=":remote" >
<intent-filter>
<action android:name="NOTIFICATION_SERVICE" />
</intent-filter>
</receiver>

Not receiving Google Cloud Messaging notifications

I am creating an application with push notification from my server. I am successful in registering the device with GCM and got the regID. Later, when I used to send the notification using the ID it’s not receiving any notification. I have listed all the code below and I am not sure where I am making mistake. Please Help me. Thank you.
Manifest
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />
<permission
android:name="com.example.mycab.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.example.mycab.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="adjustPan" />
<!-- Main activity -->
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" />
<activity
android:name=".RegisterActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="adjustPan" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<receiver
android:name=".GcmBroadcastReceiver"
android:exported="true"
android:permission="com.google.android.c2m.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.mycab" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
GcmBroadcastReceiver.java
package com.example.mycab;
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) {
System.out.println("PUSH RECEIVED!!!");
ComponentName comp = new ComponentName(context.getPackageName(),GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GCMIntentService.java
package com.example.mycab;
import com.google.android.gms.gcm.GoogleCloudMessaging;
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;
public class GCMIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
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());
} 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 < 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("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String 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.ic_home)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}

Getting Parse Push Notification in List view

I am using parse push notification for my app , the notification comes fine but on clicking the notification I need to show them in a list view , I searched for tutorials but I could not find any . Please help me . Please explain with code , I am new to android . Thanks in advance.
here is my custom receiver.
public class CustomReciever extends BroadcastReceiver {
NotificationCompat.Builder mBuilder;
Intent resultIntent;
int mNotificationId = 001;
Uri notifySound;
String alert;
#Override
public void onReceive(Context context, Intent intent) {
try{
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
alert = json.getString("alert").toString();
}catch (JSONException e){
}
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(alert));
mBuilder.setPriority(Notification.PRIORITY_HIGH);
mBuilder.setSmallIcon(R.drawable.syncytium);
mBuilder.setContentText(alert);
mBuilder.setContentTitle("Syncytium");
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setAutoCancel(true);
resultIntent = new Intent(context, com.omc.sunny.syncytium.syncytium.Notification.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(context,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId,mBuilder.build());
}
}
here is my Notification class
public class Notification extends AppCompatActivity {
TextView notifTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
notifTv = (TextView)findViewById(R.id.notif);
}
#Override
protected void onNewIntent(Intent intent) {
String message = getIntent().getExtras().getString("alert");
notifTv.setText(message);
}
}
At first add this to your manifest
-->
<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="YOURPACKAJE.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="YOURPACKAJE.permission.C2D_MESSAGE" />
add it to application tag
<service android:name="com.parse.PushService" />
<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>
<receiver
android:name="YOURPACKAJE.notifications.MyReceiver"
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="YOURPACKAJE" />
</intent-filter>
</receiver>
then create class in packaje YOURPACKAJE.notifications.MyReceiver
import java.util.List;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.TextView;
import com.parse.ParseAnalytics;
import com.parse.ParsePushBroadcastReceiver;
public class MyReceiver extends ParsePushBroadcastReceiver {
protected void onPushReceive(Context mContext, Intent intent) {
Log.e("ParsePush", "RECIVED");
if (intent.hasExtra("com.parse.Data")){
String jsonString=intent.getExtras().getString("com.parse.Data");
Log.e("", "json " + jsonString);
JSONObject json = new JSONObject(jsonString);
String title= json.getString("title");
String message= json.getString("message");
// then call your method to create manually your custom notification with pending intent
//in intent putExtra("title",title), putExtra("message",message)
//and the after opening in Activity catch this intent
}
}
}
in wersite parse.com send notification like JSON
{"title":"your tittle is here","message":"your message"}
dont use getIntent() , use intent in method:
#Override
protected void onNewIntent(Intent intent) {
String message = intent.getExtras().getString("alert");
notifTv.setText(message);
}

GCM message not arriving until App is either running or in background

I have successfully implemented GCM and messages successfully arrive to my devices when the App is in running and background states.
But when the App is in a closed state, some devices receive the message and some do not. To get the message, I have to start the application again.
Manifest:
<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" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.example.hp.abcd.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.hp.abcd.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Splash"
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=".RegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hp.abcd.REGISTER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Subject"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hp.abcd.Subject" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Message"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hp.abcd.MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver
android:name="com.example.hp.abcd.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.hp.abcd" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService" />
</application>
BroadcastReceiver:
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) {
// Waking up mobile if it is sleeping
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
GCMNotificationIntent service
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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) {
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());
} 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(""
+ extras.get(Config.MESSAGE_KEY));
Log.i(TAG, "Received: " + extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
DatabaseHandler db = new DatabaseHandler(this);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Calendar c = Calendar.getInstance();
SimpleDateFormat d = new SimpleDateFormat("dd MMMM,yyyy");
SimpleDateFormat t = new SimpleDateFormat("HH:mm");
String strDate = d.format(c.getTime());
String strTime = t.format(c.getTime());
db.addContact(new Contact(msg, strDate, strTime));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Message.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.gcm_logo)
.setContentTitle("India")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setSound(soundUri);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
}
If you "force close" an app, then it will become unresponsive to all broadcasts until the user starts it again.
If you "remove from recents" (like on some devices, long hold the "home" key) then this is not a force close, and even if the app is in the background, it will continue to receive messages.
See this post here: Will I receive GCM messages if Android kill my app and if I do a Force Close from the settings?

How to suppress Parse notification in Android while Activity is in foreground?

I am working with notification using Parse for Android Platform. I have successfully received the push notification.
I want a callback method to stop this notification while the application is running.
As of now I have tried to find, but I don't know if there is any call back method which will call on activity if notification comes. Please help me out!
In Manifest file add this in Application Tag.
<service android:name="com.parse.PushService" />
<receiver
android:name="yourPackageName.receiver.ParsePushBroadcast"
android:exported="false" >
<intent-filter>
<action android:name="yourPackageName.UPDATE_STATUS" />
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.OPEN" />
<action android:name="com.parse.push.intent.DELETE" />
</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" />
<!--
IMPORTANT: If you change the package name of this sample app,
change "com.parse.tutorials.pushnotifications" in the lines
below to match the new package name.
-->
<category android:name="yourPackageName" />
</intent-filter>
</receiver>
Add this lines above application tag in manifest file.
<permission
android:name="yourPackageName.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="yourPackageName.permission.C2D_MESSAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
Than After Create one Broadcast Receiver ParsePushBroadcast.
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.util.Log;
import com.parse.ParsePushBroadcastReceiver;
public class ParsePushBroadcast extends ParsePushBroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(final Context context, Intent intent) {
try {
String action = intent.getAction();
#SuppressWarnings("unused")
String channel = intent.getExtras().getString("com.parse.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
String title = "New alert!";
if (json.has("alert"))
title = json.getString("alert");
if (MainActivity.isActivityOpen == true) {
if (MainActivity.ACTION.equals(action))
displayAlert(context, title);
} else {
generateNotification(context, R.drawable.notification_icon, title);
}
} catch (Exception e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
#Override
protected void onPushReceive(Context context, Intent intent) {
super.onPushReceive(context, intent);
}
#SuppressWarnings("deprecation")
public static void generateNotification(Context context, int icon, String message) {
// Show the notification
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.vibrate = new long[] { 500, 500 };
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, notification);
}
private void displayAlert(Context context, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder((MainActivity) context);
builder.setTitle("Title");
builder.setMessage(title).setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
if (!alert.isShowing())
alert.show();
}
}
isActivityOpen is a static variable that I have created in Main activity. The purpose for this variable is for activity is open or not.
Important: If you have this tag in manifest Remove this tag in manifest.
<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>
In your Activity class in onResume method add that.
ParsePushBroadcast parsePushBroadcast = new ParsePushBroadcast();
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(parsePushBroadcast, filter);
add this constant in Activity
public static final String ACTION = "com.parse.push.intent.RECEIVE";

Categories

Resources