cancel intent service from broadcast broadcastreceiver - android

I'm sending a local notification with a cancel button and when I click it, I want to cancel my intent service but the event is not getting called.
I can cancel the intent service using an activity, but when is from a notification, it is not working.
My BroadcastReceiver (the Log is showing).
class EventsReceiver: BroadcastReceiver(){
var onEvent = {}
override fun onReceive(context: Context?, intent: Intent?) {
Log.i("EventsReceiver", "onReceive")
when(intent?.action){
Constants.ACTION_EVENT_CANCEL -> {
Log.i("EventsReceiver", "cancel")
onEvent()
}
}
}
}
The onReceive is getting called when I click the notification button but when I call the onEvent(), the cancelTrip() function is not getting called.
My Intent Service:
override fun onCreate() {
super.onCreate()
notificationHelper = NotificationHelper(this)
receiver = EventsReceiver ()
receiver.onEvent = {
cancelTrip()
}
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(Constants.ACTION_EVENT_CANCEL))
}
The activity function that cancels the intent service:
private fun cancel(){
val intent = Intent()
intent.setAction(Constants.ACTION_EVENT_CANCEL)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
How I create my local notification:
val notif = NotificationCompat.Builder(ctx,NOTIFICATION_CHANNEL_ID)
notif.setContentTitle("My App")
notif.setContentText("Canceled trip")
notif.setSmallIcon(R.drawable.ic_launcher_foreground)
val notifIntent = Intent(ctx, MenuActivity::class.java)
val pendingIntent = PendingIntent.getActivity(ctx,0,notifIntent,0)
notif.setContentIntent(pendingIntent)
val cancelIntent = Intent(ctx, EventsReceiver::class.java)
val cancelPendingIntent = PendingIntent.getBroadcast(ctx,0,cancelIntent,PendingIntent.FLAG_CANCEL_CURRENT)
notif.addAction(R.mipmap.ic_launcher, ctx.getString(R.string.cancel_trip), cancelPendingIntent)
service.notify(NOTIFICATION_CANCEL_ID, notif.build())

val cancelIntent = Intent(ctx, EventsReceiver::class.java)
It's because you didn't specify the action (while creating the notification) so in here when(intent?.action)
you have different action then Constants.ACTION_EVENT_CANCEL.
try using this:
val cancelIntent = Intent(Constants.ACTION_EVENT_CANCEL)
or
val cancelIntent = Intent(ctx, EventsReceiver::class.java)
cancelIntent.action = Constants.ACTION_EVENT_CANCEL

Related

Details screen Data not changes when notification tapped in Android

I was creating a simple notification app with Alarm Manager. The alarm manager trigger for 1 minute and it should give a notification. but when I tapped on the notification moves to details screen with first content.
It not changing.
Below broadcast receiver calls each 1 minute.
notification changing with different data but not in details screen. that is the problem.
AlarmReceiver
class AlarmReceiver : BroadcastReceiver()
{
override fun onReceive(context: Context?, intent: Intent?)
{
var dbHelper = context?.let { DbHelper(it) }
val question = dbHelper?.getQuestion((0..1280).random())
val i = Intent(context, SecondActivity::class.java)
i.putExtra("LAW", question)
i!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent = PendingIntent.getActivity(context, 0, i, 0)
val builder = NotificationCompat.Builder(context!!, "foxandroid")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("${question!!.type} ${question!!.code} ${question!!.subcode} ${question!!.shortDesc}")
.setContentText("${question!!.fullDesc}")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(123, builder.build())
}
}
Below class shows the notification data in detail.
Second Activity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val law = if (Build.VERSION.SDK_INT >= 33) {
intent.getSerializableExtra("LAW", Question::class.java)
} else {
intent.getSerializableExtra("LAW") as Question
}// as? Question
Log.e("law:", "${law!!.shortDesc}")
if (law != null) {
textTitle.text = "${law.type} ${law.code} ${law.subcode} ${law.shortDesc}"
}
if (law != null) {
textContent.text = law.fullDesc
}
button.setOnClickListener {
val intent= Intent(this,WebActivity::class.java)
intent.putExtra("LAW", "${law?.type} ${law?.code} ${law?.subcode}")
startActivity(intent)
}
}
}
you should use Activity#onNewIntent,
Your Activity was already created, when you start activity again,the Activity may be not run onCreate lifecycle function, and run onNewIntent. OnNewIntent somelike onCreate, they are lifecycle function.
You just try log extra bundle in Intent at OnNewIntent, and you will know.

Broadcast receiver added inside onCreate() of foreground service not working

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)

Call activity method from BroadcastReceiver Class Kotlin

I'm a beginner to Android and Kotlin. Im developing an audio player with audio controls in notification. In my Audio activity I have public methods playAudio() and pauseAudio(). I need to call this method from a broadcast receiver as below
class AudioControlsInNotification : BroadcastReceiver() {
var audioMain: Audio? = null
fun setMainActivityHandler(main: Audio) {
audioMain = main
}
override fun onReceive(context: Context?, intent: Intent?) {
if (intent != null) {
when (intent.action) {
"PAUSEAUDIO" -> {
audioMain?.pauseAudio()
}
"PLAYAUDIO" -> {
audioMain?.playAudio()
}
}
}
}
audioMain always returns null.
While clicking Play and Pause button,
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
mBuilder = NotificationCompat.Builder(applicationContext, "MYAUDIOCHANNEL")
contentView = RemoteViews(packageName, R.layout.audio_notification)
val notifyPauseIntent = Intent(this, AudioControlsInNotification::class.java).apply {
action = "PAUSEAUDIO"
}
val notifyPausePendingIntent: PendingIntent = PendingIntent.getBroadcast(this,0,notifyPauseIntent,0)
contentView!!.setOnClickPendingIntent(R.id.notifyPause, notifyPausePendingIntent)
val notifyPlayIntent = Intent(this, AudioControlsInNotification::class.java).apply {
action = "PLAYAUDIO"
}
val notifyPlayPendingIntent: PendingIntent = PendingIntent.getBroadcast(this,0,notifyPlayIntent,0)
contentView!!.setOnClickPendingIntent(R.id.notifyPlay, notifyPlayPendingIntent)
I received intent actions in the AudioControlsInNotification but i can't access the methods of Audio Activity. I tried many answers from stackoverflow but nothing helps me. I need this BroadcastReceiver on for this Audio activity only.
In my Audio activity I have public methods
That can only make sense if they are declared static in your activity class.
If they are not static then hat does not make sense as you have no pointer to your activity as activities cannot be created with the new operater but only using an intent.

requestActivityTransitionUpdates never calls the registered BroadcastReceiver

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

Prompt to unlock lock screen on custom notification click

I have a custom notification shown in the lock screen. I am using a broadcast pending intent to send a message to my app once the notification is clicked. Which later starts an activity in the broadcast receiver.
The problem is, once I click on the notification, it disappears from the lock-screen and the activity is launched behind the lock-screen. It does not ask the user to unlock the screen.
My requirement is to ask the user to unlock the screen as soon as the broadcast is sent by the notification's click event. How do I do that?
I could find this question which looks like my problem. But unfortunately there is no answer.
Here is some code that explains the notification creation I did.
/**
* Method to render Notification
*/
private void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
/* set mandatory stuff on builder */
Notification notification = builder.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification.bigContentView = createCustomView(context);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(getNotificationId(), notification);
}
/**
* Method to return notification click's PendingIntent
*/
private PendingIntent getNotificationClickIntent() {
Intent bcIntent = new Intent(OPEN_APP);
bcIntent.putExtra(EXTRA_DEEP_LINK_URL, getDeepLinkUrl());
return PendingIntent.getBroadcast(
context, getReqCode(), bcIntent, PendingIntent.FLAG_ONE_SHOT);
}
/**
* Method to create custom view for notification
*/
private RemoteViews createCustomView(Context context) {
RemoteViews customView = new RemoteViews(context.getPackageName(), R.layout.custom_layout);
if (customView != null) {
// set dat on views
customView.setOnClickPendingIntent(R.id.my_view, getNotificationClickIntent());
}
return customView;
}
Use Activity intent in pending intent instead of Service or Broadcast
PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Update:
In my case i use service.
private fun activityPendingIntent(context: Context, action: String? = null): PendingIntent {
Timber.d("activityPendingIntent")
val intent = Intent(context, DummyBackgroundActivity::class.java)
action?.let { intent.action = action }
return PendingIntent.getActivity(context, ACTIVITY_NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT)
}
DummyBackgroundActivity
class DummyBackgroundActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val service = Intent(this, BackgroundService::class.java)
service.action = intent.action
startService(service)
}
override fun onResume() {
super.onResume()
finish()
}
}
Service:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Timber.d("onStartCommand intent = %s", intent?.action)
when (intent?.action) {
//Handle it
}
return Service.START_NOT_STICKY
}
I hope you replicate the same using Broadcast.

Categories

Resources