I followed "quickstart sample" and the instructions of google cloud message latest version in link https://developers.google.com/cloud-messaging/android/client , and download project from this instructions . I succeed get device's token , and I have a php server to send to google cloud , but I can not get message from my device . Can you please here help me.
I download project from this site which is recommend in this link above
$ git clone https://github.com/googlesamples/google-services.git
Below is my server code
gcm.php
// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)
$data = array('message' => 'Hello World!');
// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/
$ids = array('foD2qlwvb9U:APA91bGOD6VD8GxGtZXmg-oFwDElMCXNOxptLXvNL3NHzKenwUYKzUFUbIapBhuuOW2ee8oC3ZUPdGRcjmOrA5B4zrzG_UQtj7soqjisM4NUHe4L4IfSjoWRiXKJfQ_918XDgX11hWdT');
// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);
function sendPushNotification($data, $ids)
{
// Insert real GCM API key from the Google APIs Console
// https://code.google.com/apis/console/
// Set POST request body
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
// Set CURL request headers
$headers = array(
'Authorization: key=AIzaSyCGw1NOaemsZWUFbUWcLCPP5p_Kcvmc9mg',
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
//curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
// Set request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set custom request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get the response back as string instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set JSON post data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// Actually send the request
$result = curl_exec($ch);
// Handle errors
if (curl_errno($ch))
{
echo 'GCM error: ' . curl_error($ch);
}
// Close curl handle
curl_close($ch);
// Debug GCM response
echo $result;
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gcm.play.android.samples.com.gcmquickstart" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<!-- [START gcm_permission] -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission android:name="gcm.play.android.samples.com.gcmquickstart.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="gcm.play.android.samples.com.gcmquickstart.permission.C2D_MESSAGE" />
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- [END gcm_permission] -->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="gcm.play.android.samples.com.gcmquickstart.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>
<!-- [START gcm_receiver] -->
<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="gcm.play.android.samples.com.gcmquickstart" />
</intent-filter>
</receiver>
<!-- [END gcm_receiver] -->
<!-- [START gcm_listener] -->
<service
android:name="gcm.play.android.samples.com.gcmquickstart.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<!-- [END gcm_listener] -->
<!-- [START instanceId_listener] -->
<service
android:name="gcm.play.android.samples.com.gcmquickstart.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<!-- [END instanceId_listener] -->
<service
android:name="gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService"
android:exported="false">
</service>
</application>
</manifest>
MyGcmListenerService.java
package gcm.play.android.samples.com.gcmquickstart;
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.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
/**
* Called when message is received.
*
* #param from SenderID of the sender.
* #param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
#Override
public void onMessageReceived(String from, Bundle data) {
Log.d(TAG, "onMessageReceived");
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// [START_EXCLUDE]
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* #param message GCM message received.
*/
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
I got the message from server :
{"multicast_id":5585998123799628757,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1464946787970982%744ab298f9fd7ecd"}]}
I googled many tutorial, blog but my device still can not get message . Do I miss something ? My internet is good because I can open webpage.
SOLVED : I change to firebase cloud message and it work.
Thanks for all friends here help me.
Try the following workarounds:
Make sure you've set your SENDER ID you've received from Google correctly.
Make sure your device was registered with Google's GCM service correctly.
Make sure you are sending the push to the correct reg id you've received from Google. and that you didn't receive an error from Google GCM service.
Change it to delay_while_idle = 0 if you want your wakelock permission to make any difference. If it was set to delay_while_idle = 1, the message won't reach the device if it's idle.
Some times it takes time for the push to arrive (but never too much time, then there is a problem). Check what's the "time to live" of the push you've sent.
You can also check these related questions:
Why I can't receive messages from GCM on android device
Can't receive messages using Google Cloud Messaging for Android (not the helper library)
can't receive messages on device using GCM
To maximise your chances of receiving the message, I would not set the time_to_live at a mere 3 seconds. I'd omit this parameter altogether so that it takes the default value of 4 weeks. I would also set delay_while to false, so that the phone gets the message even whilst idle.
Related
I would Like to listen to Alert Dialog, and i have adding an exemple but it dont work, and i cant follow the starting and capturing the event like Key Up ..etc by using Log.d.
I confirm that the Accessibility Service has Enabled, but i would like to to assure that is executing
here is my code
public class MyService extends AccessibilityService {
public static String TAG = "USD";
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.i(TAG, "onAccessibilityEvent: gettting");
String text = event.getText().toString();
if (event.getClassName().equals("android.app.AlertDialog")) {
Log.i(TAG, " Getting USSD"+text);
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
}
and the Manifest code
<service android:name=".MyService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:label=""
android:exported="false">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibility_service_config" />
</service>
and the config XML
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:packageNames="com.android.phone"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged"
android:accessibilityFlags="flagDefault"
android:accessibilityFeedbackType="feedbackGeneric"
android:notificationTimeout="0"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity"
/>
I've been trying to integrate Branch into my React Native project. I can successfully create Branch Universal Object. When I click on it, it opens the app, but the only params that the branch listener picks up are:
{"+clicked_branch_link": false, "+is_first_session": false}
Here is the relevant portion of the AndroidManifest.xml:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="branchfoodisgood" android:host="open" />
<data android:scheme="https" android:host="fig.app.link" />
<data android:scheme="http" android:host="fig.app.link" />
<data android:scheme="https" android:host="fig.test-app.link" />
<data android:scheme="http" android:host="fig.test-app.link" />
</intent-filter>
These links open on iOS with the correct data.
Interestingly when the app is no open, the link works, but when it is previously opened it does not recognize the link.
In order to work around this - I had to modify the code from the react-native branch docs.
// Override onNewIntent for Branch.io
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
/**
* Issue: The documentation provided
* (https://help.branch.io/developers-hub/docs/react-native#android) was said to
* include the followign lines:
*
* if (intent != null &&
* intent.hasExtra("branch_force_new_session") &&
* intent.getBooleanExtra("branch_force_new_session", false))
* {
* RNBranchModule.onNewIntent(intent);
* }
*
* But this was causing an issue with opening the PDP from a deep link when the
* session was already in progress
* So I remove that code and always force a new branch seesion when a link is
* opened
*
* See issue here:
* https://github.com/BranchMetrics/react-native-branch-deep-linking-attribution/issues/707
*
*/
RNBranchModule.onNewIntent(intent);
}
There is a corresponding issue here discussing this with the maintainers.
I'm developing an Android App. Users can chat each other. I fetch the messages on PushReceiver class. App opened or closed I mean foreground or background; the code block working from API 19 to API 26 but not working higher than API 26. I try to debug onReceive function but it's not call on Android O.
I want to say again. My code block working API 25 and lower versions.
I'm using pushy.me service.
My BroadcastReceiver Class:
public class PushReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String notificationTitle = "Title";
String notificationText = "Text";
Bundle bundle = intent.getExtras();
JSONObject jsonObject = new JSONObject();
for (String key : bundle.keySet()) {
try {
jsonObject.put(key, wrap(bundle.get(key)));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
notificationText = jsonObject.get("body").toString();
notificationTitle = jsonObject.get("title").toString();
} catch (Exception e) {}
// Prepare a notification with vibration, sound and lights
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setLights(Color.RED, 1000, 1000)
.setVibrate(new long[]{0, 400, 250, 400})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
// Automatically configure a Notification Channel for devices running Android O+
Pushy.setNotificationChannel(builder, context);
// Get an instance of the NotificationManager service
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Build the notification and display it
notificationManager.notify(1, builder.build());
}
}
My Manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
...
<receiver
android:name=".Notification.PushReceiver"
android:exported="false">
<intent-filter>
<!-- Do not modify this -->
<action android:name="pushy.me" />
</intent-filter>
</receiver> <!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver
android:name="me.pushy.sdk.receivers.PushyUpdateReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver> <!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver
android:name="me.pushy.sdk.receivers.PushyBootReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver> <!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService" /> <!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service
android:name="me.pushy.sdk.services.PushyJobService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE" />
Edit: pushy.me Android Demo here
The latest Pushy Android SDK has added support for Android O power saving optimizations (App Standby / deprecation of Service), please update by following the instructions on this page:
https://pushy.me/docs/android/get-sdk
Also, make sure to add the following new JobService declaration to your AndroidManifest.xml, under the <application> tag:
<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true" />
My last question was not a great question.
so here my new one.
I want to write an app that has and activity which get some info(like a phone number) from the user and then It is destroyed and the app icon is also hidden from the user.but i want to continuously receive sms from that phone number and do some stuff.
until now i have learned that if i register my broadcast receiver in the manifest it can still receive even though my app is not running or hidden.
so here is my app which i'm using xamarin (mono android):
my simple activity (it is not complete yet):
my main XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
p1:orientation="vertical"
p1:minWidth="25px"
p1:minHeight="25px"
p1:layout_width="match_parent"
p1:layout_height="match_parent"
p1:id="#+id/linearLayout1">
<EditText
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/txt_phone" />
<Button
p1:text="OK"
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/btn_ok" />
</LinearLayout>
and the activity class:
namespace SmsBroadcastReceiver
{
[Activity (Label = "SmsBroadcastReceiver", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
EditText txt_number = FindViewById<EditText> (Resource.Id.txt_phone);
Button btn_ok = FindViewById<Button> (Resource.Id.btn_ok);
btn_ok.Click += delegate {
//save the number in the sharedpreference and then...
Toast.MakeText (Context, "Your App Will be Closed now", ToastLength.Short).Show ();
};
}
}
}
now my broadcast receiver:
namespace SmsBroadcastReceiver
{
[BroadcastReceiver]
public class SmsReceiver : BroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{
Toast.MakeText (context, "sms rec", ToastLength.Long).Show ();
//get the sharedpreference and then do stuff
}
}
}
and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="SmsBroadcastReceiver.SmsBroadcastReceiver">
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="18" />
<application android:label="SmsBroadcastReceiver">
</application>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>
I know that the using a toast in a BR is not ideal but i just want to see that it is working which is not,everytime i send and sms to my phone it doesn't show anything.
where is my problem?
I think, you created BroadcastReceiver in the wrong way.
You should create it entirely with xamarin attributes.
Mono for Android translates each IntentFilterAttribute into an <intent-filter/> element.
[BroadcastReceiver]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SmsReceiver : BroadcastReceiver
{
...
}
therefore there is no need to write receiver tags manually in your AndroidManifest file.
You can also use attribute's named parameters for Priority, Categories, etc.
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = Int32.MaxValue)]
I created one remote service as follows:-
<service android:name=".XYZService"
android:permission="com.xyz.service"
android:exported="true">
<intent-filter>
<action android:name="com.abc.def.XYZService"/>
</intent-filter>
</service>
I am trying to bind with this service by using client application service as follows:-
//client service onStartCommand code :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean ret;
try {
Intent i = new Intent("com.abc.def.XYZService");
ret = getApplicationContext().bindService(i, serviceConnection,
Context.BIND_AUTO_CREATE);
if (ret == false) {
//log error
}
} catch (SecurityException e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
client application manifest has following permission:-
<uses-permission android:name="com.xyz.service" />
Still, I am getting following exception:-
Security Exception: The client Service does not have permission to bind to the xyz service.
My intention here is to protect my exported service with some permission and use that permission in client application to access exported service.
Any help will be appreciated.
Use this.
<permission
android:name="myPermission"
android:description="#string/myPermissionDescription"
android:label="#string/myPermissionLabel">
</permission>
more info:
page 1 --
page 2