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(),
GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GCMNotificationIntentService.java
import android.app.ActivityManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.json.JSONObject;
import java.util.List;
import vmasurat.cygnus.com.vmasurat.ConstantData;
import vmasurat.cygnus.com.vmasurat.CustomeObject.MemberProfile;
import vmasurat.cygnus.com.vmasurat.Popup2;
import vmasurat.cygnus.com.vmasurat.R;
import vmasurat.cygnus.com.vmasurat.Util;
public class GCMNotificationIntentService extends IntentService {
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super(ConstantData.GOOGLE_PROJECT_ID);
}
public static final String TAG = "GCMNotificationIntentService";
String message = "";
String fromid = "";
String type = "";
@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)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
for (String key : extras.keySet()) {
Object value = extras.get(key);
Log.d("TAG", String.format("%s %s (%s)", key, value.toString(), value
.getClass().getName()));
}
try {
message = intent.getExtras().getString("message");
JSONObject notificationobj = new JSONObject(message);
message = notificationobj.getString("m");
fromid = notificationobj.getString("n");
type = notificationobj.getString("t");
// Log.v("BODId", "" + intent.getExtras().getString("BODId"));
MemberProfile m = MemberProfile.getMemberProfileFromString(Util.getSharePrefranceData(GCMNotificationIntentService.this, ConstantData.SHARED_PREFERENCES_Profile_Object));
if (m != null) {
if (isAppIsInBackground(GCMNotificationIntentService.this) == true) {
sendNotification("" + message);
} else {
Intent i = new Intent(this, Popup2.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ConstantData.jsonmsg = message;
ConstantData.fromname = fromid;
ConstantData.type = type;
startActivity(i);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE);
// Toast.makeText(GCMNotificationIntentService.this, msg, Toast.LENGTH_LONG).show();
Intent in = new Intent(GCMNotificationIntentService.this, Popup2.class);
// in.putExtra("Userid", fromid);// in.putExtra("message", message);// in.putExtra("type", type);
ConstantData.jsonmsg = message;
ConstantData.fromname = fromid;
ConstantData.type = type;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, in, 0);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.vmalogo)
.setContentTitle(getString(R.string.app_name))
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setAutoCancel(true)
.setContentText(msg)
.setColor(Color.RED)
.setContentIntent(contentIntent)
.setNumber(2);
mNotificationManager.notify(1000, mBuilder.build());
} else {
Notification notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentText(msg)
.setSmallIcon(R.drawable.vmalogo)
.setNumber(3)
.setContentIntent(contentIntent)
.setColor(Color.RED)
.build();
mNotificationManager.notify(1000, notification);
}
}
public static boolean isAppInForeground(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return MyLifecycleHandler.isApplicationInForeground();
} else {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (topActivity.getPackageName().equals(
context.getPackageName())) {
return true;
}
}
}
return false;
}
private boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
}
MyLifecycleHandler.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
@TargetApi(14)
public class MyLifecycleHandler implements ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
@Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override public void onActivityDestroyed(Activity activity) {
}
@Override public void onActivityResumed(Activity activity) {
++resumed;
}
@Override public void onActivityPaused(Activity activity) {
++paused;
}
@Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override public void onActivityStarted(Activity activity) {
++started;
}
@Override public void onActivityStopped(Activity activity) {
++stopped;
}
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
return resumed > paused;
}
}
RegisterGCM.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.json.JSONObject;
import java.io.IOException;
import vmasurat.cygnus.com.vmasurat.ConstantData;
/** * Created by Hitz on 22-Jun-15. */public class RegisterGCM {
public static String REG_ID = "regId";
private Context context;
private String regId;
private GoogleCloudMessaging gcm;
public RegisterGCM(Context context) {
this.context = context;
if (TextUtils.isEmpty(regId)) {
regId = registerGCM();
Log.d("RegisterActivity", "GCM RegId: " + regId);
} else {
// Toast.makeText(context,// "RegId already available. RegId: " + regId,// Toast.LENGTH_LONG).show(); }
}
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
RegisterGCM.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i("REG:-->", "Registration not found.");
return "";
}
return registrationId;
}
public static String registerUserForPushNotification(String deviceToken, Context context, String userId, boolean islogin) {
JSONObject requestData = new JSONObject();
try {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
final String deviceId = telephonyManager.getDeviceId();
requestData.put("userid", userId);
requestData.put("deviceId", deviceId);
requestData.put("regId", islogin ? deviceToken : "");//regid
Log.e("Data-->", "Mai n data push notifcation " + requestData.toString());
} catch (Exception e) {
e.printStackTrace();
}
final AQuery aq = new AQuery(context);
aq.post(ConstantData.UpdateToken, requestData, JSONObject.class, new AjaxCallback<JSONObject>(
) {
public void callback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
try {
if (json.getString(ConstantData.RESULT).equalsIgnoreCase("success")) {
JSONObject jsonData = json.getJSONObject(ConstantData.DATA);
if (!jsonData.getBoolean(ConstantData.TOKEN)) {
// Toast.makeText(aq.getContext(), jsonData.getString(ConstantData.MESSAGE), Toast.LENGTH_LONG).show(); }
} else {
// Toast.makeText(aq.getContext(), "Error :" + json.toString(), Toast.LENGTH_LONG).show(); }
} catch (Exception ex) {
// Toast.makeText(aq.getContext(), "Error :" + json.toString(), Toast.LENGTH_LONG).show(); }
} else {
// Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show(); }
}
});
return "";
}
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(context);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("RegisterActivity",
"registerGCM - successfully registered with GCM server - regId: " + regId);
} else {
// Toast.makeText(context,// "RegId already available. RegId: " + regId,// Toast.LENGTH_LONG).show(); }
return regId;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(ConstantData.GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
@Override protected void onPostExecute(String msg) {
// Toast.makeText(context,// "Registered with GCM Server." + msg,// Toast.LENGTH_LONG).show(); saveRegisterId(context, regId);
}
}.execute(null, null, null);
}
private void saveRegisterId(Context context, String regId) {
final SharedPreferences prefs = context.getSharedPreferences(
RegisterGCM.class.getSimpleName(), Context.MODE_PRIVATE);
Log.i("Saved:-->", "Saving regId on app version ");
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.commit();
}
}
call 1st time
RegisterGCM.registerUserForPushNotification(RegisterGCM.getRegistrationId(getActivity()).toString(), getActivity(), memberProfile.getInqID(), false);
Constantdata.java
public static final String GOOGLE_PROJECT_ID = "8048969903541243w5";
public static final String RESULT = "result";
// public static final String SearchProfile = "SearchProfile";public static final String DATA = "data";
public static final String MESSAGE = "Message";
public static final String TOKEN = "Token";
menifiest.xml
<receiver android:name=".broadcastreceiver.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" android:screenOrientation="portrait">
<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="vmasurat.cygnus.com.vmasurat" />
</intent-filter>
</receiver>
<service android:name=".broadcastreceiver.GCMNotificationIntentService" android:enabled="true" android:screenOrientation="portrait" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
------secondWay----------
GCMClientManager.java
**
* Created by hiteshsarkheliya on 16/03/16.
*/
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regid;
private String projectNumber;
private Activity activity;
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regid = getRegistrationId(getContext());
if (regid.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regid);
handler.onSuccess(regid, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
InstanceID instanceID = InstanceID.getInstance(getContext());
regid = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, regid);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regid);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regid;
}
@Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(),
Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
}
PushNotification.java
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.google.android.gms.gcm.GcmListenerService;
import com.isk.behero.Common.Utils;
import java.util.List;
/**
* Created by hiteshsarkheliya on 16/03/16.
*/
public class PushNotification extends GcmListenerService {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onMessageReceived(String from, Bundle data) {
final String pushmessage = data.getString("message");
final String fromd=from;
if (Utils.isAppIsInBackground(PushNotification.this))
{
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
new AlertDialog.Builder(PushNotification.this)
.setTitle("" + pushmessage)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
};
}
else
{
Intent intent=new Intent(PushNotification.this,HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(PushNotification.this, (int) System.currentTimeMillis(), intent, 0);
Notification n = new Notification.Builder(PushNotification.this)
.setContentTitle(""+pushmessage)
.setSmallIcon(R.mipmap.hero_hoodies)
.setContentIntent(pIntent).build();
NotificationManager notificationManager =
(NotificationManager) PushNotification.this.getSystemService(PushNotification.this.NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
}
resister notication
private void registerNotification()
{
GCMClientManager pushClientManager = new GCMClientManager(this, Constant.PROJECT_NUMBER);
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
@Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id",registrationId);//eTtH4OOYfm8:APA91bG3FEjoR0gGfs78dvyA-1DFxlDSlf7F8DrN1vJjnvyGBi6ZbdwGcqAeu2piQ15YQWDNwdXILK-lQHMBKrkwYg2KOSEkW6QSDKTlQbZyOLst7vDXYCXsJL4unN4h2WYGJJeOjbtz
if (Utils.isInternetConnected(HomeActivity.this))
{
AjaxCallback<JSONObject> respoce = new AjaxCallback<JSONObject>() {
public void callback(String url, JSONObject json, AjaxStatus status) {
Log.d("Responce",""+status);
try {
Type type = new TypeToken<ParseResponceObject>() {
}.getType();
ParseResponceObject parseResponceObject = new Gson().fromJson(String.valueOf(json), type);
if (parseResponceObject.getResult().equalsIgnoreCase("success") &&
parseResponceObject.getFlag().equalsIgnoreCase("true"))
{
}
else
{
Toast.makeText(HomeActivity.this,"Error Push : "+status,Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
JSONObject requestData=new JSONObject();
try {
requestData.put(RequestServices.KEY_USER_ID,Constant.Login_User.getMain_user_id());
requestData.put(RequestServices.KEY_device_id,Constant.DEVICE_ID);
requestData.put(RequestServices.KEY_device_token,registrationId);
requestData.put(RequestServices.KEY_device_type,"android");
requestData.put(RequestServices.KEY_certificate_type,Constant.CERTIFICATE_TYPE.DEV);
} catch (JSONException e) {
e.printStackTrace();
}
RequestServices.callService(HomeActivity.this,RequestServices.REGISTER_TOKEN,requestData,respoce);
}
else
{
Toast.makeText(HomeActivity.this,"Please connect to the network.",Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(String ex) {
Log.i(Constant.APPTAG,""+ex);
super.onFailure(ex);
}
});
}
menifiest.xml
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />
<service android:name=".PushNotification" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</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" />
<category android:name="com.isk.behero" />
</intent-filter>
</receiver>
Comments
Post a Comment