What I need is when the user clicks on a button, a push notification will be sent to all users using this app.
I tried using this code in a setOnclickListener method, but nothing was sent after clicking on it.
Note: Sending a push notification from Parse Dashboard works perfectly
fine.
ParsePush parsePush = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
parsePush.setQuery(query);
parsePush.setMessage("A new file has been Updated. Check it out!");
parsePush.sendInBackground(new SendCallback() {
#Override
public void done(ParseException arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "SendCallback success:");
if(arg0 == null)
{
Log.d(TAG,
"suceess push notification :");
}
else
{
Log.d(TAG,
"failed push notification :"
+ arg0.getMessage());
}
}
});
}
});
- EDIT - in response to Bradley Wilson's answer
- this still did not work
ParsePush parsePush = new ParsePush();
ParseQuery<ParseInstallation> parseQueryInstallation = ParseQuery.getQuery(ParseInstallation.class);
parsePush.setQuery(parseQueryInstallation);
parsePush.setMessage("A new file has been Updated. Check it out!");
parsePush.sendInBackground(new SendCallback() {
#Override
public void done(ParseException arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "SendCallback success:");
if(arg0 == null)
{
Log.d(TAG,
"suceess push notification :");
}
else
{
Log.d(TAG,
"failed push notification :"
+ arg0.getMessage());
}
}
- EDIT 2 - in response to Suresh Kumar's answer
- For some reason, cloud code never works in my projects. It just doesn't identify any Cloud code and keeps it in red as shown in this image
The better way to send push notification in Parse is through cloud code. Create a cloud function to send push notification and call that cloud function in android using ParseCloud.callFunctionInBackground().
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("recipientId", userObject.getObjectId());
params.put("message", message);
ParseCloud.callFunctionInBackground("sendPushToUser", params, new FunctionCallback<String>() {
void done(String success, ParseException e) {
if (e == null) {
// Push sent successfully
}
}
});
Take a look at this link
Related
I have a piece of code that do not work, and I cannot understand why. As the subject says, it logs in to Twitter, but redirects back to the sign in button. setupTimeline(); is never executed.
I am using twitter4j library, it is at the latest version, 4.0.7.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the preferences for the app.
tweetzPrefs = getSharedPreferences("TweetzPrefs", 0);
// Find out if the user preferences are set.
if (tweetzPrefs.getString("user_token", null) == null) {
// No user preferences so prompt to sign in.
setContentView(R.layout.activity_main);
// Get a twitter instance for authentication.
tweetzTwitter = new TwitterFactory().getInstance();
// Pass developer key and secret.
tweetzTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
// Try to get request token.
try {
new Thread(new Runnable() {
#Override
public void run() {
try {
// Get authentication request token.
tweetzRequestToken = tweetzTwitter.getOAuthRequestToken(TWIT_URL);
Log.e(LOG_TAG, "Are we there Yeti?");
} catch (TwitterException e) {
e.printStackTrace();
Log.e(LOG_TAG, "TwitterException: " + e.getMessage());
}
if (tweetzRequestToken == null) {
Log.e(LOG_TAG, "tweetzRequestToken == null.");
}
}
}).start();
// Get authentication request token.
// tweetzRequestToken = tweetzTwitter.getOAuthRequestToken(TWIT_URL);
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG, "Exception: " + e.getMessage());
}
// Setup button for click listener.
Button signIn = (Button) findViewById(R.id.signin);
signIn.setOnClickListener(this);
} else {
// User preferences are set, get timeline.
setupTimeline();
}
}
Any ideas anyone?
Regards.
I'm trying to manage in-app billing in my app and i used to succeed and get the in-app tester payment window but after a while im always getting this type of resultcode from the purchase which is :
BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED 7 - Failure to purchase since item is already owned
is there any way to prevent from this to happen?
Purchase purchasePremium = null;
// The helper object
IabHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
{
// Create the helper, passing it our context and the public key to verify signatures with
Log.d(TAG, "Creating IAB helper.");
mHelper = new IabHelper(this, base64EncodedPublicKey);
}
public void onConsumePremiumButtonClicked(View arg0) {
if(purchasePremium != null)
{
Log.d(TAG, "We have Premium. Consuming it.");
try {
mHelper.consumeAsync(purchasePremium, mConsumeFinishedListener);
} catch (IabHelper.IabAsyncInProgressException e) {
complain("Error consuming Premium. Another async operation in progress.");
writeToLogFile("\nError consuming Premium. Another async operation in progress.");
}
}
else
{
alert("Please Subscribe the Product before Consuming it.",TAG,ActivityPurchaseManagedProduct.this);
}
}
// Called when consumption is complete
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result);
// if we were disposed of in the meantime, quit.
if (mHelper == null) return;
if (result.isSuccess()) {
// successfully consumed, so we apply the effects of the item in our
// game world's logic, which in our case means filling the Premium tank a bit
alert(" Consume Premium Success full",TAG,ActivityPurchaseManagedProduct.this);;
purchasePremium = null;
}
else {
complain("Error while consuming: " + result);
}
Log.d(TAG, "End consumption flow.");
}
};
I just set up GCM in my Android App. But I have the problem that I don't know how to check if the device is already registered. I work with the new google play services library.
The register part looks like this:
#Override
protected String doInBackground(String... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context_app);
}
regid = gcm.register(SENDER_ID);
msg = "Dvice registered, registration ID=" + regid;
Log.d("111", msg);
sendRegistrationIdToBackend(regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
How can I modify this that it checks if the device is already registered?
Store the registration id in a databade table or shared preference and when app starting..check whether it is null or not
Google has provided very clear documentation with code.You should use following code:
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
when you get registration Id, Store it in SharedPreferences, for example:
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",MODE_PRIVATE);
SharedPreferences.Editor editor=shp.edit();
editor.putString("RegID",registrationID).commit;
In the next time before you register check the "anyNameYouLike" if it contain field called RegID Like this:
private boolean isRegistered(Context context){
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",PRIVATE_MODE);
return shp.contains("RegID");
}
I am writing an android application to get the Facebook user albums and photos and display in my Android application.
I have created a Facebook App with APP_ID 281846961912565.
While creating the Facebook instance, I am passing this id as follows
facebook = new Facebook(APP_ID);
Using this instance, I am able to login to my FB account post on messages on facebook wall programatically.
After logging in, I get an access_token.
I'm using the access token to get the album ids using facebook.request("https://graph.facebook.com/me/albums?access_token="+facebook.getAccessToken());
Now I get {"error":{"message":"Malformed access token ACCESSTOKENACCESSTOKEN?access_token=ACCESSTOKENACCESSTOKEN","type":"OAuthException","code":190}}
Can any of you please help me resolve this issue and point out what i am doing wrong.
My code is as follows:
private static final String[] PERMISSIONS = new String[] { "publish_stream","user_photos" };
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY,
Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null) {
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
}
R.layout.facebook_dialog is the dialog which pops up asking if a message should be shared on facebook or not. If yes the following method is called.
public void share(View button) {
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
getImagesFromUserAlbum();
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
Later when I do a `private void getImagesFromUserAlbum() {
facebook.getAccessToken();
JSONArray albumss = null;
String response = null;
try {
response = facebook.request("me/albums");
// `
I get the error
{"error":{"message":"Malformed access token ACCESSTOKEN?access_token=ACCESSTOKEN","type":"OAuthException","code":190}}
Thanks for your help.
The code above is now the working copy. Thanks to Bartek.
If you look at the Errors page in the documentation you will see that when you get error 190 you should authorise/reauthorise the user.
I suspect that this happened to you because you first logged in, then added the permissions to access the albums to your application BUT did not log out and log back in. Hence, you need to obtain a new access token which will grant the new permissions to your application.
Please check is there &expires in your access token if yes then remove it because it is not part of access_token and try after that.
i develop the application that has Google API so i can put map in my app
i have problem in get user Current location, i want :
when the user open map Activity it display the map and marker on her location.i already doing google API stuff but i faced problem with USER CURRENT LOCATION AND MARKER ON IT.
this is my code(it is shows me in ocean !!):
alert.setButton2("get an address",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6,touchedPoint.getLatitudeE6() / 1E6,1);
OverlayItem overlayItem = new OverlayItem( touchedPoint, "Whats up", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d,MapsActivity.this);
custom.insertPinpoint(overlayItem);
overlaylist.add(custom);
if (address.size() > 0) {
String display = "";
for (int i = 0; i < address.get(0)
.getMaxAddressLineIndex(); i++) {
display += address.get(0)
.getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(
getBaseContext(), display,
Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});
i Have a nightmare about Map, PLEASE FIX MY CODE
please check below example
1) http://eagle.phys.utk.edu/guidry/android/mapOverlayDemo.html
2) http://androidmyway.wordpress.com/2012/02/26/map-marker-dragging
in second one you can check how to get address.
Thank You
if you just want to show users current location you could use MyLocationOverlay class in mapactivity.
it will draw the marker on the location itself.