How Can I Use BroadcastReceiver on API 26 and Higher? - api

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" />

Related

How to add an service accessibility Android that registre Alert Dialog

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"
/>

Foreground Service Not Updating Sensors Data In Background

I am new in Android Development, I've created an application with API version 29 using Kotlin. My main activity is launching a Foreground Service which is doing the following tasks.
Getting Location using the FusedLocationProviderClient.
Getting Sensor Data (Accelerometer and Gyroscope)
Showing the above information in a Notification
The application is supposed to get the Location and Sensors information in the background and update the Notification.
The Application is currently updating the Sensors and Location data when the Main Activity application is running. Once the Main Activity is closed, the Location data gets updated in the Notification but the Sensor data is not being updated. I've read some QnA sessions (including this) but I'm unable to figure out the issue.
Code To Launch Service:
val serviceIntent = Intent(this, MyBackgroundService::class.java);
serviceIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
startForegroundService(serviceIntent);
Permissions & Features in Manifest:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="true" />
Foreground Service in Manifest:
<service android:name=".MyBackgroundService"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="location"
android:icon="#drawable/logo"
android:process=":MyBackgroundServiceProcess"/>
I am wondering if there is any foregroundServiceType to continuously get the Sensor values when the Main Activity is closed.

Android 7 open APK with ACTION_VIEW not working (Package installer has stopped)

My app has an auto update feature which download an APK and then uses a Intent.ACTION_VIEW to open the package installer.
Up to 7 it worked perfectly (by feeding the Intent with a normal file://)
With Android 7 I had to change to use a FileProvider. The only difference in the code is:
Intent installIntent = new Intent(Intent.ACTION_VIEW);
if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
installIntent.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
} else {
Uri apkUri = FileProvider.getUriForFile(AutoUpdate.this,
BuildConfig.APPLICATION_ID, file);
installIntent.setDataAndType(apkUri,manager.getMimeTypeForDownloadedFile(downloadId));
}
activity.startActivity(installIntent);
Once the startActivity is called I get this every single time
Is this a bug with Android 7 ? Or something/permission is missing my side ?
EDIT AndroidManifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_LOGS" />
<application ...>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp"
android:exported="false"
android:enabled="true"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
The path xmlfile
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="myfolder" path="."/>
</paths>
try like below, it helped me and its working in Android N7.0.
File toInstall = new File(appDirectory, appName + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivity(intent);
} else {
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
Try to add read uri permission to your intent:
installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Check this answer
https://stackoverflow.com/a/40131196/1912947

google cloud message 3.0 device not receive message

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.

android.intent.action.CAMERA_BUTTON not broadcasting on Desire Z (Froyo)?

I have hard time intercepting HW camera button on Desire Z (Froyo). I wrote a sample that runs fine on G1 (1.6) but not on aforementioned phone.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.company" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".CameraReceiverTestActivity"
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:enabled="true" android:exported="true"
android:name=".CameraButtonReceiver">
<intent-filter android:priority="999">
<action android:name="android.intent.action.CAMERA_BUTTON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
And CameraButtonReceiver.java
package net.company;
public class CameraButtonReceiver extends BroadcastReceiver {
static {
Log.w("CBR", "onReceive clazz init");
}
#Override
public void onReceive(Context context, Intent intent) {
Log.w("CBR", "onReceive camera");
abortBroadcast();
}
}
On G1 (1.6) I see both messages as soon as press the camera button and default camera app is suppressed. However, on Desire Z (Froyo) no such thing happens. After playing with priority, code/xml declarations I dare to say this phone sends this broadcast with some other name.
There is no requirement for a device manufacturer to send any broadcast when the CAMERA button is clicked, from my reading of the Compatibility Definition Document. It might only be used by the foreground activity on the Desire Z. I don't have a Z and so cannot confirm your tests.
Since the vast majority of Android devices do not have a CAMERA button at all, you will need to ensure that your app works well without such a button, and that you advise users that the CAMERA button may or may not work with your app depending upon device.