Scenario: The below mentioned code snippet shows a BroadcastReciver whose work is to start a service whenever the added geonfence is entered. A JobIntentService is then initiated which does some operation with the passed on string, and then triggers notification with the data.
What needs to be done: I want that, among many other added geofences, when a specific geofence is triggered, it should be removed to prevent from retriggering.
Question: How to implement this in above mentioned scenario?
Below is the screenshot for reference
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_GEOFENCE_EVENT) {
val geoFencingEvent = GeofencingEvent.fromIntent(intent)
if (geoFencingEvent.hasError()) {
Timber.i("Error while activating Geofencing: ${geoFencingEvent.errorCode}")
return
} else {
val geoFenceTransition = geoFencingEvent.geofenceTransition
if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
val geofenceId = geoFencingEvent.triggeringGeofences[0].requestId
val jobIntent = Intent(context, GeofenceTransitionsJobIntentService::class.java)
.putExtra("REMINDER_ID", geofenceId)
GeofenceTransitionsJobIntentService.enqueueWork(context, jobIntent)
}
}
}
}
}
Related
Broadcast receiver class inside the service
inner class ServiceNotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent!!.action
Util.log("action from foreground services")
when (action) {
FOREGROUND_NEXT -> {
next()
}
FOREGROUND_PREVIOUS -> {
prevoius()
}
FOREGROUND_PLAY_PAUSE -> {
if (exoPlayer.isPlaying) {
pause()
} else {
play()
}
}
FOREGROUND_STOP -> {
stopSelf()
}
}
}
}
I am registering it inside the onCreate() of the service like so
serviceNotificationListener = ServiceNotificationReceiver()
val intentfliter = IntentFilter().apply {
addAction(FOREGROUND_PLAY_PAUSE)
addAction(FOREGROUND_PREVIOUS)
addAction(FOREGROUND_NEXT)
addAction(FOREGROUND_STOP)
}
this.registerReceiver(serviceNotificationListener, intentfliter)
The pending intent
playintent = Intent(this, ServiceNotificationReceiver::class.java).setAction(
FOREGROUND_PLAY_PAUSE
)
playpendingIntent =
PendingIntent.getBroadcast(this, 0, playintent, PendingIntent.FLAG_UPDATE_CURRENT)
I am adding it as an action inside the notification builder like so
addAction(
com.google.android.exoplayer2.R.drawable.exo_icon_previous,
"Previous",
previouspendingIntent
)
However the clicks are not registering inside the service. I cannot add it in the manifest due to some complexity in the app and this is the only way. So what could be the issue. Is it the flags or something else.
You're setting your intent target component to yourpackage.YourService.ServiceNotificationReceiver which is not registered in manifest, system will not be able to resolve it and nothing is executed.
Modify your intent to target only your apps package then your receiver will be able to match it:
playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)
I am playing around with Wear OS on a Fossil Falster 3 (it is running API 28). Also please know that I am just starting with Kotlin, so the code below is not good to say the least.
I want to create a Geofence using broadcast receiver.
In my MainActivity.kt I have the following:
override fun onStart() {
super.onStart()
requestForegroundAndBackgroundLocationPermissions()
val locations = arrayOf(Location("tgh", 58.798233, 11.123959))
val geofences = locations.map {
Geofence.Builder()
.setRequestId(it.name)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setCircularRegion(it.latitude, it.longitude, 100F)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
.setLoiteringDelay(10)
.build()
}
val geofencingRequest = GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofences)
}.build()
val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceReceiver::class.java)
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
val geofencingClient = LocationServices.getGeofencingClient(this)
geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent).run {
addOnFailureListener {
// display error
exception -> Log.d(TAG, "addOnFailureListener Exception: $exception")
}
addOnSuccessListener {
// move on
Log.d(TAG, "addOnSuccessListener, move on")
}
}
}
The GeofenceReceiver is in the same file:
class GeofenceReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
Log.d(TAG, "geofencingEvent.hasError()")
} else {
geofencingEvent.triggeringGeofences.forEach {
val geofence = it.requestId
Log.d(TAG, "location at: " + geofence)
}
}
}
}
The manifest has the following snippet:
<receiver android:name=".GeofenceReceiver"
android:enabled="true"
android:exported="true"/>
That is pretty much it. When I run the code, addOnFailureListener is triggered and the error message is printed and it is resulting in a 1000 exception.
Exception 1000 according to google documentation means GEOFENCE_NOT_AVAILABLE. I have enabled location on both the watch and the phone to its highest level on phone (Improve Location Accuracy is ON). On the watch I have set to use location from both watch and phone (highest level). Still I keep getting the 1000 error code.
I am coding a simple app that measures all available sensors of the android device (Wifi, BT, etc). One of them is the user activity (via ActivityRecognition API), but I can't make it works properly.
I code a class to do everything related to user activity. I want to get only 4 states and one attribute to store the current one:
var VEHICLE = "vehicle"
var WALKING = "walking"
var STILL = "still"
var UNKNOWN = "unknown"
private var current: String? = null
It also includes a BroadcastReceiver object to handle activity transitions:
private var recognitionHandler = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
val result = ActivityRecognitionResult.extractResult(intent)
val activity = result.mostProbableActivity
current = when(activity.type) {
DetectedActivity.IN_VEHICLE,
DetectedActivity.ON_BICYCLE -> VEHICLE
DetectedActivity.WALKING,
DetectedActivity.RUNNING -> WALKING
DetectedActivity.STILL -> STILL
else -> UNKNOWN
}
}
}
}
The class also have two methods to define the intent and request:
private fun createIntent() : PendingIntent {
val intent = Intent(context, recognitionHandler.javaClass)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
context.registerReceiver(recognitionHandler, IntentFilter())
return pendingIntent
}
private fun createRequest() : ActivityTransitionRequest {
val types = listOf(
DetectedActivity.IN_VEHICLE,
DetectedActivity.WALKING,
DetectedActivity.RUNNING,
DetectedActivity.ON_BICYCLE,
DetectedActivity.STILL
)
val transitions = mutableListOf<ActivityTransition>()
types.forEach { activity ->
transitions.add(
ActivityTransition.Builder()
.setActivityType(activity)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build()
)
}
return ActivityTransitionRequest(transitions)
}
And also one to start listening:
override fun start(onResult: (res: String?) -> Unit) {
// ...
intent = createIntent()
val request = createRequest()
ActivityRecognition.getClient(context)
.requestActivityTransitionUpdates(request, intent)
.addOnSuccessListener {
Log.d("UserActivity Service info", "listening...")
}
.addOnFailureListener { e ->
Log.d("UserActivity Service error", e.toString())
}
// ...
}
The problem is that the current attribute is always null. I think I have some issues with intent or handler registration, but I have no idea where.
Does someone have any comments? :)
Thanks!
This is your problem. In this code from createIntent():
val intent = Intent(context, recognitionHandler.javaClass)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
context.registerReceiver(recognitionHandler, IntentFilter())
return pendingIntent
You return a PendingIntent that you use in the call to requestActivityTransitionUpdates(). However, that PendingIntent refers to a dynamically created inner class (your BroadcastReceiver) and Android cannot instantiate that class.
You also additionally call registerReceiver(), however you pass an empty IntentFilter in that call so the registered BroadcastReceiver is never called.
To fix the problem, you can either provide a correctIntentFilter that matches your PendingIntent OR you can refactor your BroadcastReceiver into a proper class (not a private inner class) and make sure that you've added the BroadcastReceiver to your manifest and make it publicly available (exported="true").
Here's an example of how to do this using a BroadcastReceiver:
https://steemit.com/utopian-io/#betheleyo/implementing-android-s-new-activity-recognition-transition-api
Initially I setup a BroadcastReceiver to receive intents from the Nearby Messages API.
class BeaconMessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Nearby.getMessagesClient(context).handleIntent(intent, object : MessageListener() {
override fun onFound(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Found iBeacon=$id")
sendNotification(context, "Found iBeacon=$id")
}
override fun onLost(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Lost iBeacon=$id")
sendNotification(context, "Lost iBeacon=$id")
}
})
}
private fun sendNotification(context: Context, text: String) {
Timber.d("Send notification.")
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = NotificationCompat.Builder(context, Notifications.CHANNEL_GENERAL)
.setContentTitle("Beacons")
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification_white)
.build()
manager.notify(NotificationIdGenerator.nextID(), notification)
}
}
Then registered this receiver in my MainActivity after location permissions have been granted.
class MainActivity : AppCompatActivity() {
// ...
private fun onLocationPermissionsGranted() {
val filter = MessageFilter.Builder()
.includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
.build()
val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()
Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
}
private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
this, 0, Intent(context, BeaconMessageReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
This worked well while the app was open, but does not work when the app is closed. So I found this example, that demonstrates how to setup an IntentService to receive messages while the app is in the background.
The example does use the Nearby.Messages class, which was deprecated in favor of the MessagesClient. So I replaced the deprecated code with the MessagesClient implementation.
class MainActivity : AppCompatActivity() {
// ...
private fun onLocationPermissionsGranted() {
val filter = MessageFilter.Builder()
.includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
.build()
val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()
Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
.addOnSuccessListener {
Timber.i("Subscribed successfully.")
startService(Intent(this, BeaconMessageIntentService::class.java))
}.addOnFailureListener {
Timber.e(exception, "Subscription failed.")
}
}
private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
this, 0, Intent(context, BeaconMessageIntentService::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
And this is the IntentService (which is almost identical to my BroadcastReceiver).
class BeaconMessageIntentService : IntentService("BeaconMessageIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.let {
Nearby.getMessagesClient(this)
.handleIntent(it, object : MessageListener() {
override fun onFound(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Found iBeacon=$id")
sendNotification("Found iBeacon=$id")
}
override fun onLost(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Lost iBeacon=$id")
sendNotification("Lost iBeacon=$id")
}
})
}
}
private fun sendNotification(text: String) {
Timber.d("Send notification.")
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = NotificationCompat.Builder(this, Notifications.CHANNEL_GENERAL)
.setContentTitle("Beacons")
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification_white)
.build()
manager.notify(NotificationIdGenerator.nextID(), notification)
}
}
onHandleIntent is called, and the Intent is not null; yet for some reason onFound() and onLost() are never called. Why would this be the case?
It's not really a solution but what I found is this (credit to this answer):
I've tried a few configurations including a BroadcastReceiver and adding a JobIntentService to run the code in the background, but every time I got this the onExpired callback which you can set to the SubscribeOptions:
options.setCallback(new SubscribeCallback() {
#Override
public void onExpired() {
super.onExpired();
Toast.makeText(context.get(), "No longer Subscribing!", Toast.LENGTH_SHORT).show();
}
}
When the subscribe occurred in the background it was delayed, but it was still called.
Notes:
1. When I've tested with Strategy.BLE_ONLY I did not get the onFound callback.
2. From Google's documentation:
Background subscriptions consumes less power than foreground
subscriptions, but have higher latency and lower reliability
When testing I found this "lower reliability" to be an understatement: onFound was rarely called and I never got the onLost.
I know this is a late reply, but I had the same problem and found out by debugging that it is an issue related to this error: "Attempting to perform a high-power operation from a non-Activity Context". This can be solved when calling Nearby.getMessagesClient(this) by passing in an activity context instead of this.
In my case I added a class extending Application which helps in returning this context (the below is in java but should be translatable to kotlin easily)
public class MyApplication extends Application {
private Activity currentActivity = null;
public Activity getCurrentActivity(){
return currentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.currentActivity = mCurrentActivity;
}
}
And in my base activity, from which all activities extend, I set the current activity by calling ((MyApplication) this.getApplicationContext()).setCurrentActivity(this); in the constructor.
My service can then call getMessagesClient with the correct context like below:
final Activity context = ((MyApplication)getApplicationContext()).getCurrentActivity();
Nearby.getMessagesClient(context).[...]
Do not forget to register your Application class in the AndroidManifest:
<application
android:name="com.example.xxx.MyApplication"`
I show a notification with actions to the user, I handle these actions with a BroadcastReceiver, from there I update a realm database, but it doesn't get updated, even though I'm sure(through logs) the transaction gets executed.
NotificationBroadcastReceiver:
override fun onReceive(context: Context, intent: Intent) {
val notionId = intent.getStringExtra(NOTION_ID_EXTRA)
val actionType = intent.getIntExtra(ACTION_TYPE, ACTION_TYPE_PUTBACK)
when (actionType) {
ACTION_TYPE_PUTBACK -> {
Toast.makeText(context, R.string.notion_is_putback, Toast.LENGTH_SHORT).show()
}
ACTION_TYPE_ARCHIVE -> {
NotionsRealm.changeIdleState(notionId, true)
}
}
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(NotionsReminder.NOTION_NOTIFICATION_ID)
}
NotionsRealm:
fun changeIdleState(id: String, state: Boolean) {
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
val notion = it.where<Notion>().equalTo("id", id).findFirst()
notion?.isArchived = state
debug("${notion?.isArchived}") //prints true to the log, but the data doesn't change.
}
closeRealm(realm)
}
private fun closeRealm(realm: Realm) {
try {
realm.close()
} catch (e: Exception) {
error(e)
} finally {
debug("realm closed")
}
}
edit:
I just let the receiver start an empty activity(with no layout) to handle the database. the same thing happened. I think it's no longer a BroadcastReceiver issue. It's strange, other realm transactions run perfectly in other activities/fragments.
Turns out it's not a problem with realm, it was How I fired the broadcast, I did it this way:
fun notificationAction(context: Context, id: String, actionType: Int): PendingIntent {
return PendingIntent.getBroadcast(
context, actionType,
Intent(context, NotificationBroadcastReceiver::class.java).apply {
putExtra(NotificationBroadcastReceiver.NOTION_ID_EXTRA, id)
putExtra(NotificationBroadcastReceiver.ACTION_TYPE, actionType)
}, 0)
}
I found that the passed id was incorrect, after some searching I found out that I should include this flag in the broadcast: PendingIntent.FLAG_UPDATE_CURRENT so it's like this:
fun notificationAction(context: Context, id: String, actionType: Int): PendingIntent {
return PendingIntent.getBroadcast(
context, actionType,
Intent(context, NotificationBroadcastReceiver::class.java).apply {
putExtra(NotificationBroadcastReceiver.NOTION_ID_EXTRA, id)
putExtra(NotificationBroadcastReceiver.ACTION_TYPE, actionType)
}, PendingIntent.FLAG_UPDATE_CURRENT)
}
Now the passed id is the right one, I still don't understand why did this happen, or why was the id extra completely different(yet not random, I kept seeing the same wrong id every time) without this flag.