here i am really not getting why my code is not sending push from a user to another user ,i can send and receive pushes by sending through channels but problem is i get push notification to all user, not the specific user ,how can i send from a user to another user here below is my code please explain me what is my mistake ,or how to me it work
MY onClick of button where things must happen
ok.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final String currentUserId = ParseUser.getCurrentUser().getObjectId();
ParseQuery<ParseUser> query = ParseUser.getQuery();
getPhone = phone.getText().toString();
//for not including myself
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("username", getPhone);
query.getFirstInBackground(new GetCallback<ParseUser>()
{
public void done(final ParseUser user, ParseException e)
{
if (user == null)
{
Toast.makeText(Welcome.this, "couldnot connect to " + getPhone, Toast.LENGTH_SHORT).show();
Log.d("username", "problem retriving username");
}
else
{
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereEqualTo("email", "three");
final String name = user.getUsername();
String data = "{\n" +
"\"data\":{\n "+
"\"message\":\"Connection request\",\n" +
"\"title\":\"Connection\",\n" +
"\"from\":"+"\""+ParseUser.getCurrentUser().getUsername()+"\""+"\n "+
"}\n" +
"}";
JSONObject jsonObject = null ;
try
{
jsonObject = new JSONObject(data);
} catch (JSONException e1)
{
e1.printStackTrace();
}
ParsePush push = new ParsePush();
push.setQuery(pushQuery);
push.setData(jsonObject);
//push.setChannel("Giants");
push.sendInBackground(new SendCallback()
{
#Override
public void done(ParseException e)
{
if (e == null)
{
Toast.makeText(getApplicationContext(), "request send to "+name, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "problem sending request to "+name+" due to "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
);
Intent i = new Intent(Welcome.this, TestActivity.class);
Log.e("about user", "connected to " + user.getUsername());
retrivedUser = user.getUsername();
i.putExtra("number", retrivedUser);
startActivity(i);
}
}
});
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!--
IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
to match your app's package name + ".permission.C2D_MESSAGE".
-->
<permission android:protectionLevel="signature"
android:name="com.parse.starter.permission.C2D_MESSAGE" />
<uses-permission android:name="com.example.chattapp.permission.C2D_MESSAGE" />
<application
android:name=".Chattapp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name" />
<activity android:name=".DispatchActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name=".Welcome" />
<activity android:name=".TestActivity"></activity>
<service android:name="com.parse.PushService" />
<!--<receiver android:name="com.parse.ParsePushBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>-->
<receiver android:name="com.example.chattapp.CustomReceiver"
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" />
<!--IMPORTANT: Change "com.parse.starter" to match your app's package name.-->
<category android:name="com.example.chattapp" />
</intent-filter>
</receiver>
</application>
here is the push image
push details
This is what I did for a chat app I made, every time a user sings up on your app, suscribe it to a channel with their user id. That way you will have an unique channel for every user and you can send individual pushes to them.
Here is a quick code I put up:
ParseUser user = new ParseUser();
user.setUsername("my name");
user.setPassword("my pass");
user.setEmail("email#example.com");
// other fields can be set just like with ParseObject
user.put("phone", "650-253-0000");
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
String userID = user.getObjectId();
ParsePush.subscribeInBackground(userID});
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
After this you just need the userid of the receiver and that's it.
Is client push enabled in the parse application settings ?
It's disabled by default.
More infomation can be found at the parse blog:
http://blog.parse.com/learn/engineering/the-dangerous-world-of-client-push/
Related
I am trying to send user to user notification on click of a button to specific users but getting this issue while sending notification from last 4 days in android, and with this, whenever i uninstall the app from my phone which i am using as emulator, and reinstall it for debugging, it doesnt create new installation id and take the old one: i Guess this is the problem, please it will be great help if anybody help me in a elaborated way
Here is my code of custom reciever:
public class CustomPushReceiver extends ParsePushBroadcastReceiver {
private final String TAG = CustomPushReceiver.class.getSimpleName();
private NotificationUtils notificationUtils;
private Intent parseIntent;
public CustomPushReceiver() {
super();
}
#Override
protected void onPushReceive(Context context, Intent intent) {
super.onPushReceive(context, intent);
if (intent == null)
return;
try {
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
Log.e(TAG, "Push received: " + json);
parseIntent = intent;
parsePushJson(context, json);
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
#Override
protected void onPushDismiss(Context context, Intent intent) {
super.onPushDismiss(context, intent);
}
#Override
protected void onPushOpen(Context context, Intent intent) {
super.onPushOpen(context, intent);
}
/**
* Parses the push notification json
*
* #param context
* #param json
*/
private void parsePushJson(Context context, JSONObject json) {
try {
boolean isBackground = json.getBoolean("is_background");
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
if (!isBackground) {
Intent resultIntent = new Intent(context, MainActivity.class);
showNotificationMessage(context, title, message, resultIntent);
}
} catch (JSONException e) {
Log.e(TAG, "Push message json exception: " + e.getMessage());
}
}
/**
* Shows the notification message in the notification bar
* If the app is in background, launches the app
*
* #param context
* #param title
* #param message
* #param intent
*/
private void showNotificationMessage(Context context, String title, String message, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.putExtras(parseIntent.getExtras());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, intent);
}
}
and my ParseQuery:
try {
ParseQuery userQuery = new ParseQuery(ParseUser.class);
userQuery.whereNear("Location",
currentUser.getParseGeoPoint("Location"));
userQuery.setLimit(10);
userQuery.whereEqualTo("Type", "Doctor");
userQuery.whereEqualTo("deviceType", "android");
userQuery.findInBackground();
// Find devices associated with these users
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereMatchesQuery("user", userQuery);
// Send push notification to query
ParsePush push = new ParsePush();
push.setQuery(pushQuery);
push.setMessage("Only users near"
+ currentUser.getParseGeoPoint("Location")
+ " will recieve this push notification");
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Notification Sent", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getApplicationContext(),
"Notification not Sent",
Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aspire.wecare"
android:versionCode="1"
android:versionName="1.0" >
<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.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.aspire.wecare.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.aspire.wecare.permission.C2D_MESSAGE" />
<permission
android:name="com.aspire.wecare.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.aspire.wecare.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<application
android:name="com.aspire.wecare.ParseApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.aspire.wecare.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.aspire.wecare.Welcome"
android:label="#string/title_activity_welcome" >
</activity>
<activity
android:name="com.aspire.wecare.LoginActivity"
android:label="#string/title_login" >
</activity>
<activity
android:name="com.aspire.wecare.LoginSignupActivity"
android:label="#string/title_activity_login_signup" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBA3_YfEl2cnZ8uDmrI23g8W7l1y2Xiku8" />
<!-- Added for Parse push notifications -->
<service android:name="com.parse.PushService" />
<receiver
android:name=".receiver.CustomPushReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.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.aspire.wecare" />
</intent-filter>
</receiver>
<!-- /Added for Parse push notifications -->
</application>
</manifest>
In general terms,
(1) you would be doing this in cloud code. Fortunately it's very easy once you get started. In fact here is a total explanation from a similar question.
https://stackoverflow.com/a/32540054/294884
Muhc more importantly though,
(2) be aware you're using the wrong tool for the job. You do not use 'Push' for what you are trying to achieve. You should be using PubNub, Firebase, Pusher or a similar service. It is commonplace to use one of these in combination with Parse.
i have try to implement GCM in android studio got below error in my logcat.
LogCat:
onReceive: com.google.android.c2dm.intent.REGISTRATION GCM
IntentService class: com.project.GCMIntentService Acquiring wakelock
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project">
<permission
android:name="com.project.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.project.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<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="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.project.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<permission
android:name="com.project.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:name="com.project.App"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreenActivity"
android:screenOrientation="portrait"
android:theme="#style/FullScreenThemes">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.project.core.account.ManageAccounts" />
<activity android:name=".projectActivity"/>
<activity android:name=".projectLogin"/>
<activity android:name="fieldatom.controls.SearchableItemActivity" />
<activity android:name="com.project.SettingsActivity" />
<activity
android:name="com.project.core.account.AppIntro"
android:screenOrientation="portrait" />
<activity
android:name=".base.addons.mail.widget.MailDetailDialog"
android:theme="#style/Theme.AppCompat.Light.Dialog" />
<activity
android:name=".base.addons.mail.widget.MailChatterCompose"
android:theme="#style/Theme.AppCompat.Light.Dialog" />
<activity
android:name=".core.account.FieldAtomAccountQuickManage"
android:theme="#style/Theme.AppCompat.Light.Dialog"
android:windowSoftInputMode="adjustPan" />
<activity android:name="com.project.core.account.About" />
<activity android:name="com.project.core.account.Profile" />
<!-- Reminder Receivers// -->
<receiver android:name="com.project.core.utils.reminder.ReminderReceiver" />
<receiver android:name="com.project.core.utils.reminder.ReminderActionReceiver" />
<!--<receiver android:name=".server.notifications.OdooServerNotificationReceiver">
<intent-filter>
<action android:name="com.project.odoo.mobile.SERVER_NOTIFICATION" />
</intent-filter>
</receiver>-->
<service android:name="com.project.core.auth.OdooAuthService">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="#xml/authenticator" />
</service>
<provider
android:name="com.project.core.orm.provider.BaseModelProvider"
android:authorities="com.project.core.provider.content"
android:multiprocess="true" />
<provider
android:name="com.project.base.addons.ir.providers.IrModelProvider"
android:authorities="com.project.core.provider.content.sync.ir_model"
android:multiprocess="true" />
<!-- Sync Customer Provider & Service // -->
<provider
android:name="com.project.addons.customers.providers.CustomersSyncProvider"
android:authorities="com.project.core.provider.content.sync.res_partner"
android:label="#string/sync_label_customers"
android:multiprocess="true" />
<service
android:name="com.project.addons.customers.services.CustomerSyncService"
android:exported="true"
android:process=":sync_customer">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/customer_sync_adapter" />
</service>
<!-- Sync Request Provider & Service // -->
<provider
android:name="com.project.addons.requests.providers.RequestSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_service_request"
android:label="#string/sync_label_request"
android:multiprocess="true" />
<service
android:name="com.project.addons.requests.services.RequestSyncService"
android:exported="true"
android:process=":sync_request">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/request_sync_adapter" />
</service>
<!-- Sync Stage Provider & Service // -->
<provider
android:name="com.project.addons.stages.providers.StageSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_service_stage"
android:label="#string/sync_label_stages"
android:multiprocess="true" />
<service
android:name="com.project.addons.stages.services.StageSyncService"
android:exported="true"
android:process=":sync_stage">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/stage_sync_adapter" />
</service>
<!-- Sync Account Analytic Provider & Service // -->
<provider
android:name="com.project.addons.accountanalytics.providers.AccountAnalyticSyncProviders"
android:authorities="com.project.core.provider.content.sync.account_analytic_line"
android:label="#string/sync_label_accountAnalytic"
android:multiprocess="true" />
<service
android:name="com.project.addons.accountanalytics.services.AccountAnalyticSyncService"
android:exported="true"
android:process=":sync_account_analytic">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/account_analytic_sync_adapter" />
</service>
<!-- Sync Product Provider & Service // -->
<provider
android:name=".addons.products.providers.ProductsSyncProviders"
android:authorities="com.project.core.provider.content.sync.product_product"
android:label="#string/sync_label_product"
android:multiprocess="true" />
<service
android:name=".addons.products.service.ProductsSyncService"
android:exported="true"
android:process=":sync_account_analytic">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/product_sync_adapter" />
</service>
<!-- Sync QUOTATION Provider & Service // -->
<provider
android:name=".addons.quotes.providers.QuotationSyncProviders"
android:authorities="com.project.core.provider.content.sync.sale_order"
android:label="#string/sync_label_quotation"
android:multiprocess="true" />
<service
android:name=".addons.quotes.services.QuotationSyncService"
android:exported="true"
android:process=":sync_quotation">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/quote_sync_adapter" />
</service>
<!-- Sync QUOTATIONLine Provider & Service // -->
<provider
android:name=".addons.quotes.providers.QuotationLineSyncProviders"
android:authorities="com.project.core.provider.content.sync.sale_order_line"
android:label="#string/sync_label_quotation_line"
android:multiprocess="true" />
<service
android:name=".addons.quotes.services.QuotationLineSyncService"
android:exported="true"
android:process=":sync_quotation_line">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/quote_line_sync_adapter" />
</service>
<!-- Sync Attachment Provider & Service // -->
<provider
android:name=".addons.attachment.providers.IrAttachmentSyncProviders"
android:authorities="com.project.core.provider.content.sync.ir_attachment"
android:label="#string/sync_label_attachment"
android:multiprocess="true" />
<service
android:name=".addons.attachment.service.IrAttachmentSyncService"
android:exported="true"
android:process=":sync_attachment">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/attachment_sync_adapter" />
</service>
<!-- Sync MailMessage Provider & Service // -->
<provider
android:name=".base.addons.mail.providers.MailMessageSyncProviders"
android:authorities="com.project.core.provider.content.sync.mail_message"
android:label="#string/sync_label_mail_message"
android:multiprocess="true" />
<service
android:name=".base.addons.mail.service.MailMessageSyncService"
android:exported="true"
android:process=":sync_mail_message">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/mail_message_sync_adapter" />
</service>
<!-- Sync Maps Provider & Service // -->
<provider
android:name=".addons.maps.providers.MapsSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_map"
android:label="#string/sync_label_map_message"
android:multiprocess="true" />
<service
android:name=".addons.maps.service.MapsSyncService"
android:exported="true"
android:process=":sync_map">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/maps_sync_adapter" />
</service>
<service android:name=".addons.requests.services.TimeUpdateService"></service>
<activity
android:name="com.project.addons.customers.CustomerDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden|adjustPan" />
<activity
android:name=".addons.requests.utils.RequestTabDetailAcitivty"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden|adjustPan"
/>
<activity
android:name=".addons.accountanalytics.VisitDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:theme="#style/CustomActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".addons.accountanalytics.CreateVisitActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddPartActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddNoteActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddQuoteActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.utils.CaptureSignature"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.utils.ProductRequestListActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.quotes.QuoteDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.products.ProductDetails"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<!-- Map Related Metadata -->
<uses-library
android:name="com.google.android.maps"
android:required="false" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCpjJtPYoeVN2dGqCVMCDEoR847OEwzgME" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- Push Notification -->
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.project" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService"></service>
</application>
<!--CB:A6:E7:26:97:08:37:4A:D6:60:1B:9B:2C:D0:9A:3B:9F:DF:02:D3;com.project-->
</manifest>
This is my project structure details below.
com.projcet
App.java
ProjcetLogin.java
GCMIntentService.java
This code working perfect in eclipse & android studio...finally i can do it.
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener{
//Notification Constant
Context context;
Button btn_GCMRegister, btn_Post;
GoogleCloudMessaging gcm;
public static String URL = "192.168.1.39:12069";
String regId;
public final String GOOGLE_PROJECT_ID = "your project id";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
init();
}
private void init() {
btn_GCMRegister = (Button) findViewById(R.id.btn_gcm_register);
btn_GCMRegister.setOnClickListener(this);
btn_Post = (Button) findViewById(R.id.btn_post_on_server);
btn_Post.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_gcm_register:
registerGCM();
break;
case R.id.btn_post_on_server:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Map<String, Object> params = new HashMap<String, Object>();
params.put("regId", regId);
params.put("user_id", 1);
String server_url = URL;
try {
post(server_url, params);
}catch (IOException e){
e.printStackTrace();
}
break;
default:
break;
}
}
/*
* Issue a POST request to the server.
*/
private static void post(String endpoint, Map<String, Object> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Map.Entry<String, Object> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
//Log.v(Config.TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
System.out.println("Json Data--->" + status);
// If response is not success
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private void registerGCM() {
// TODO Auto-generated method stub
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GOOGLE_PROJECT_ID);
Log.d("Reg Id----->", "" + regId);
Toast.makeText(MainActivity.this,"Register Key from server : " +regId,Toast.LENGTH_LONG).show();
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("MainActivity", "Error: " + msg);
}
Log.d("MainActivity", "AsyncTask completed: " + msg);
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered On GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
#Override
protected void onError(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onError", "gcm...error");
}
public GCMIntentService() {
super("your project id");
}
#Override
protected String[] getSenderIds(Context context) {
return super.getSenderIds(context);
}
#Override
protected void onMessage(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "Received message");
if (intent.getExtras() != null) {
String message = intent.getExtras().getString("message");
String title = intent.getExtras().getString("title");
String ticker = intent.getExtras().getString("ticker");
generateNotification(context,message,title,ticker);
}
}
#Override
protected void onRegistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onRegistered", "gcm Registered");
}
#Override
protected void onUnregistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onUnregistered", "gcm...Unregistered...");
}
/**
* Create a notification to inform the user that server has sent a message.
*/
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static void generateNotification(Context context, String message,String title,String ticker) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
builder.setContentTitle(title)
.setContentText(message)
.setLargeIcon(
BitmapFactory.decodeResource(context.getResources(),
icon))
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(intent).setSmallIcon(icon).setTicker(ticker)
.setLights(0xff00ff00, 300, 100)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE).setAutoCancel(true).setWhen(when);
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xxx.gcmnotification" >
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.example.xxx.gcmnotification.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.xxx.gcmnotification.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.xxx.gcmnotification" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
build.gradle(Module:app)
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.google.android.gms:play-services:+'
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="#+id/btn_gcm_register"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:text="Register On GCM Server" />
<Button
android:id="#+id/btn_post_on_server"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:text="Post On Server" />
</LinearLayout>
I am developing simple android app and very new to parse. I followed parse documentation in adding back-end functionalities. Parse CORE was an easy part but I can’t send push notifications from android device. But push-notifications are received when sent from parse dashboard.
My Manifest file is as below:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.SEND" />
<!--
IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
to match your app's package name + ".permission.C2D_MESSAGE".
-->
<permission android:protectionLevel="signature"
android:name="loaniistar.loaniistar.permission.C2D_MESSAGE" />
<uses-permission android:name="loaniistar.loaniistar.permission.C2D_MESSAGE" />
<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="com.parse.ParsePushBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!--
IMPORTANT: Change "com.parse.starter" to match your app's package name.
-->
<category android:name="loaniistar.loaniistar" />
</intent-filter>
</receiver>
Application Class:
public class MApplication extends Application {
String applicationiId = "5npdddECsGdDk49OttttuHq6iZdZpddI0cHDsz";
String clientKey = "SjF1BWamssstycthSjf2dddduhcuwW2VccccCCuFlE";
public UserAccounts userAccount = null;
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
ParseCrashReporting.enable(this);
Parse.initialize(this, applicationiId, clientKey);
PushService.startServiceIfRequired(this);
}
}
Subscribing for channel in an activity class:
ParsePush.subscribeInBackground("manager", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
}
else
{
btnLoginEnable();
}
}
});
Sending Push Notification in another activity class:
// Sending Push
ParsePush push = new ParsePush();
push.setChannel("manager");
push.setMessage(m.getMessage().substring(0, (int) m.getMessage().length() / 3));
//push.sendInBackground();
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
if(e == null)
{
Toast.makeText(getActivity(), "Notification sent", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "Notification Not sent", Toast.LENGTH_SHORT).show();
}
}
});
Row is added in “Installation” class and GCMSenderId is empty!! Is this the issue?
Please help me out why I can’t receive notifications when sent from my android device?
Libs used:
Bolts-android-1.1.4.jar
Parse-1.8.2.jar
ParseCrashReporting-1.8.2.jar
If you have just created the App in Parse and integrated in your App, It generally not works immediately Same thing happened to me. I was not getting the data, but after some time I got the requests when I saw the Parse Dashboard
It will take Approx 20 mins. You can try to see the Parse Analytics.(if you have implemented it) if Parse shows Requests in your Analytics Dashboard then It will work completely fine
I use parse.com api.
What my problem is :
When other client send push notification I did not receive anything on my broadcastreceiver.
My manifest
<service android:name="com.parse.PushService" />
<receiver
android:name=".MainActivity$MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="com.yy.xx.UPDATE_STATUS" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
and my receiver in mainactivity is here:
public static class MyReceiver extends BroadcastReceiver {
public final String TAG = "MyReceiver";
#Override
public void onReceive(Context context, Intent intent) {
//this is not working,
try {
if (intent == null)
{
Log.d(TAG, "Receiver intent null");
}
else
{
String action = intent.getAction();
if (action.equals("com.yy.xx.UPDATE_STATUS"))
{
//....
}
}
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
}
and my push notification send code is here:
JSONObject obj;
try {
obj =new JSONObject();
obj.put("action","com.yy.xx.UPDATE_STATUS");
obj.put("customdata","message...");
push_p = new ParsePush();
#SuppressWarnings("rawtypes")
ParseQuery query = ParseInstallation.getQuery();
// Notification for Android users
//query.whereEqualTo("deviceType", "android");
push_p.setQuery(query);
push_p.setData(obj);
push_p.setChannel("channel_111");
push_p.sendInBackground();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I read parse.com api and tutorial but I do not understand what is the problem.
thanks in advance
Add all this declarations in manifest
<!-- PARSE SERVICE AND RECEIVERS -->
<service
android:name="com.parse.PushService"
android:enabled="true" />
<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="com.parse.GcmBroadcastReceiver"
android:enabled="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.app" />
</intent-filter>
</receiver>
<receiver android:name=".MainActivity$MyReceiver" >
<intent-filter>
<action android:name="com.example.update.UPDATE_STATUS" />
</intent-filter>
</receiver>
And add permissions
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.example.app.permission.C2D_MESSAGE" />
<permission
android:name="com.example.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
I am trying to implement parse push notification in my android project. to understand, I am giving some project flow.
saving user details on personal server using php API
server send me some push notification.
I get notification but I am not getting any action, data in that push notification in my custom broadcast receiver.
Here is my Android Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA" />
<permission
android:name="com.mypackage.myapp.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.mypackage.myapp.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:name="com.mypackage.myappe.MyApplication"
android:allowBackup="true"
android:icon="#drawable/dwtlogo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name="com.parse.PushService" />
<receiver
android:name="com.mypackage.myapp.MyCustomReceiver"
android:exported="false" android:enabled="true">
<intent-filter>
<action android:name="com.mypackage.myapp.MESSAGE" />
</intent-filter>
</receiver>
<category android:name="com.mypackage.myapp" />
</application>
Here is MyApplication.java
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "xxxxxxxx", "xxxxxxxxxx");
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
PushService.setDefaultPushCallback(getApplicationContext(), DashBoardActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
ParseUser.enableAutomaticUser();
//String deviceToken= (String) installation.get("deviceToken");
//Toast.makeText(this, "Device token="+deviceToken, Toast.LENGTH_LONG).show();
PushService.subscribe(this, "Wake_up", DashBoardActivity.class);
}
And here is my custom receiver in which i am trying to get action and data which server sending me but my custom receiver not getting called.
String action = intent.getAction();
Log.d(TAG, "got action " + action );
if (action.equals("com.mypackage.myapp.MESSAGE"))
{
String channel = intent.getExtras().getString("com.parse.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
Log.d(TAG, "got action " + action + " on channel " + channel + " with:");
Iterator itr = json.keys();
while (itr.hasNext()) {
String key = (String) itr.next();
//if (key.equals("customdata"))
//{
Intent pupInt = new Intent(context, ShowPopup.class);
pupInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
context.getApplicationContext().startActivity(pupInt);
//}
Log.d(TAG, "..." + key + " => " + json.getString(key));
}
}
}
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
Even no any log getting printed. Here is php server code which sending me push notification.
$data = array(
'channel' => $chnl,
'action' => 'com.mypackage.myapp.MESSAGE',
'data' => array(
'alert' => $message,
'sound' => 'push.caf',
'photourl' => $imageurl,
)
);
But i don't understand where i need to get this data so i can show image after receiving push notification.
Please give me any hint or reference.
Adding receiver for GcmBroadcastReceiver should help. As given out in the tutorial here.
Other reference.
<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="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: Change "com.parse.tutorials.pushnotifications" to match your app's package name.
-->
<category android:name="com.parse.tutorials.pushnotifications" />
</intent-filter>
</receiver>