Foreground Service Not Updating Sensors Data In Background - kotlin

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.

Related

How to connect wifi with NetworkSpecifier?

Permission(AndroidManifest.xml)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
WifiConnector.kt
val builder = WifiNetworkSpecifier.Builder()
builder.setSsid("test1234")
builder.setWpa2Passphrase("12345678")
val wifiNetworkSpecifier = builder.build()
val networkRequestBuilder1 = NetworkRequest.Builder()
networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier)
val nr = networkRequestBuilder1.build()
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
cm.bindProcessToNetwork(network)
}
}
cm.requestNetwork(nr, networkCallback);
Test device android version
Android API 29
Hello
I used WifiNetworkSpecifier to connect to a specific Wifi.
https://developer.android.com/guide/topics/connectivity/wifi-bootstrap
I made it by referring to the document
The message appears.
"Something came up. The application has cancelled the request to choose a device"
I think the app is printing the message because it doesn't have the necessary permissions to connect to WiFi.
If you know why it's not working, please let me know

How Can I Use BroadcastReceiver on API 26 and Higher?

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

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

MonoDroid device registeration for push notifications using PushSharp

In my monodroid application I have a problem registering some devices for push notifications using pushSharp. My general push notification setup works fine on newer devices such as SGS2, SGS3 and Nexus7, however on Legend and Hero running 2.2 and 2.2.1 the registration fails in release (works fine in debug).
I have narrowed down the problem to the StartService call:
var intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.SetPackage(GSF_PACKAGE);
intent.PutExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
PendingIntent.GetBroadcast(context, 0, new Intent(), 0));
intent.PutExtra(GCMConstants.EXTRA_SENDER, senders);
context.StartService(intent);
The manifest file looks fine:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
...
<!-- Google Cloud Messaging (GCM) for push messages -->
<permission android:name="my.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="my.package.name.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
The intent looks fine (act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf) and the senderId is correct, but the GCMIntentService OnReceive method is never triggered...
Sometimes the following error message can be seen using logcat (although not consistently):
E/C2DMRegistrar( 302): [C2DMReg] handleRequest caught java.io.IOException: SSL shutdown failed: I/O error during system call, Broken pipe.
I am not really sure how to solve this problem and would appreciate any help.
Thanks
Peter
You don't need these permissions as they should be set within your pushsharp code...
<permission android:name="my.package.name.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="my.package.name.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

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.