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.
Related
I have a list view in my home screen widget and I want to launch a pending intent when the item is clicked. I referred to this and set a fillInIntent for every list item and then set a pending intent template which triggers the broadcast receiver of the widget:
class WidgetProvider : HomeWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
appWidgetIds.forEach { widgetId ->
val views = RemoteViews(context.packageName, R.layout.widget_layout).apply {
val todosStr = widgetData.getString("todos", "null")
val todos = ArrayList<HashMap<String, Any>>()
val todosRemoteView = RemoteViews.RemoteCollectionItems.Builder()
if(todosStr != "null"){
val jObj = JSONObject(todosStr)
val jsonArry = jObj.getJSONArray("todos")
for (i in 0 until jsonArry.length()) {
val todo = HashMap<String, Any>()
val obj = jsonArry.getJSONObject(i)
todo["id"] = obj.getInt("id")
todos.add(todo)
val view = RemoteViews(context.packageName, R.layout.each_todo).apply {
setTextViewText(R.id.each_todo_container_text, todo["taskName"].toString())
val fillInIntent = Intent().apply {
Bundle().also { extras ->
extras.putInt("todo_id", todo["id"].toString().toInt())//this isn't working for some reason
putExtras(extras)
}
}
Log.d("debugging", "id received is ${todo["id"].toString()}" )
setOnClickFillInIntent(R.id.each_todo_container_text, fillInIntent)
}
todosRemoteView.addItem(todo["id"].toString().toInt().toLong(), view)
}
}
setRemoteAdapter(
R.id.todos_list,
todosRemoteView
.build()
)
val pendingIntentx: PendingIntent = Intent(
context,
WidgetProvider::class.java
).run {
PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE or Intent.FILL_IN_COMPONENT)
}
setPendingIntentTemplate(R.id.todos_list, pendingIntentx)
}
appWidgetManager.updateAppWidget(widgetId, views)
}
}
override fun onReceive(context: Context?, intent: Intent?) {
val viewIndex: Int = intent!!.getIntExtra("todo_id", 0)
Log.d("debugging", "an item is clicked $viewIndex")
//the default value gets used, which means that the receiver isn't receiving the intent data
super.onReceive(context, intent)
}
}
The problem is that the receiver isn't receiving the data which was put in the fillInIntent, the default value 0 is getting printed by the last statement. I also tried setting the FILL_IN_COMPONENT flag as suggested here, but that didn't work. Where am I going wrong?
I'm trying to use WorkManager instead of a Foreground Service. But I have a problem when I add createCancelPendingIntent() as an Intent action for the notification. When I click "Cancel" Button in the notification, the Worker stops but the notification does not get dismissed unless I start the Worker again, wait until it's done and send another notification with the same ID but with setOngoing(false).
This is my code:
class DownloadWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
private val notificationManager = ContextCompat
.getSystemService(
applicationContext,
NotificationManager::class.java
) as NotificationManager
override suspend fun doWork(): Result {
fakeDownload()
notificationManager.sendNotification(
"Download complete!",
applicationContext)
return Result.success()
}
private suspend fun fakeDownload() {
for (progress in 0..100 step 10){
delay(1000)
setForeground(createForeground(progress))
}
}
private fun createForegroundInfo(progress: String): ForegroundInfo {
// Pending Intent to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(getId())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel()
}
val notification = NotificationCompat.Builder(applicationContext, id)
.setContentTitle("Downloading")
.setContentText(progress)
.setSmallIcon(R.drawable.ic_work_notification)
.setOngoing(true)
// Add the cancel action to the notification which can
// be used to cancel the worker
.addAction(android.R.drawable.ic_delete, "Cancel", intent)
.build()
return ForegroundInfo(0, notification)
}
}
Stopping the worker from the notification works by raising an exception. You need to catch the exception in the usual kotlin way, then manually clear the notification.
A few more details are here: https://stackoverflow.com/a/66900141
override suspend fun doWork(): Result {
return try {
set foreground
do work
Result.success() [or failure, as applicable]
} catch (e: Exception) {
Result.success() [or failure, as applicable]
} finally {
clean up...
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll() [or cancel(id) for more targetted operation]
Log.d(tag, "finally")
}
}
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
New to Android development and I’m trying out the latest addHistoricMessage, and I’m missing something because it’s not displaying anything. On rare occasion the addMessage text is displayed, but the addHistoricMessage is never displayed. addMessage works consistently when using NotificationCompat, but NotificationCompat doesn’t appear to have addHistoricMessage.
Any thoughts appreciated - using androidx.appcompat:appcompat:1.0.2 and compileSdkVersion and targetSdkVersion are both 28.
An example of what I’m seeing is:
Test button that calls notification:
fun test(view: View) {
val job = GlobalScope.launch {
val repository = DataRepository.getInstance(Db.getDb(this#MainActivity))
AlarmReceiver().notifyTest(
this#MainActivity,
repository.upcomingDetail(9),
arrayListOf("Hi!", "Miss you!", "Hello!")
)
}
}
Notification methods and related (less important code removed):
fun notifyTest(context: Context, upcoming: UpcomingDetail, top3Sent: List<String>?) {
//...
#TargetApi(Build.VERSION_CODES.P)
when (Build.VERSION.SDK_INT) {
in 1..27 -> {
with(NotificationManagerCompat.from(context)) {
notify(upcoming.id.toInt(), legacyNotificationBuilder(
context,
upcoming,
noteIntent,
contentPending,
disablePending,
deletePending,
postponePending,
top3Sent
).build())
}
}
else -> context.getSystemService(NotificationManager::class.java)
.notify(upcoming.id.toInt(), notificationBuilder(
context,
upcoming,
noteIntent,
contentPending,
disablePending,
deletePending,
postponePending,
top3Sent
).build())
}
}
#RequiresApi(Build.VERSION_CODES.P)
private fun notificationBuilder(
context: Context,
upcoming: UpcomingDetail,
noteIntent: Intent,
contentPending: PendingIntent,
deletePending: PendingIntent,
disablePending: PendingIntent,
postponePending: PendingIntent,
top3Sent: List<String>?
): Notification.Builder {
val recipient: android.app.Person = android.app.Person.Builder().setName("Darren").setImportant(true).build()
val you: android.app.Person? = null
val messageStyle = Notification.MessagingStyle(recipient)
val message1 = Notification.MessagingStyle.Message("Hello!", Instant.now().minusSeconds(10 * 60).toEpochMilli(), recipient)
messageStyle.addHistoricMessage(message1)
messageStyle.addMessage(Notification.MessagingStyle.Message("Hi", Instant.now().toEpochMilli(), recipient))
val remoteInput: android.app.RemoteInput = android.app.RemoteInput.Builder(upcoming.id.toString()).run {
top3Sent?.let { setChoices(top3Sent.toTypedArray()) }
build()
}
//...
val inputAction = Notification.Action.Builder(0, context.getString(R.string.button_edit), inputPending).run {
addRemoteInput(remoteInput)
build()
}
return Notification.Builder(context, "Input").apply {
setSmallIcon(R.drawable.ic_stat)
style = messageStyle
setAutoCancel(true)
setCategory(Notification.CATEGORY_REMINDER)
setColor(ContextCompat.getColor(context, R.color.secondaryDarkColor))
setContentIntent(contentPending)
setDeleteIntent(deletePending)
setGroup("notifications")
setOnlyAlertOnce(true)
setVisibility(Notification.VISIBILITY_PRIVATE)
addAction(inputAction)
}
}
This is the behavior of historic message
Historic message is not normally shown at the notification. It is a special message that is only shown when user is replying through a RemoteInput. See the image above to see the behaviour. It should only be used when the message is not the main subject of the notification but may give context to a conversation.
Reference: Android MessagingStyle Notification As Clear As Possible
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"`