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)
Related
I am using a broadcast receiver to exchange data between a service and the MainActivity, but the receiver doesn't receive anything. Does anyone know what's the problem here?
Receiver code:
private var broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val extras = intent.extras
if(extras != null){
when(extras.getString("message")){
"lock_phone" -> devicePolicyManager.lockNow()
"block_touch" -> devicePolicyManager.setKeyguardDisabled(adminComponent,true)
"unblock_touch" -> devicePolicyManager.setKeyguardDisabled(adminComponent,false)
}
}
}
}
Sender code:
class WatchService : WearableListenerService() {
override fun onMessageReceived(messageEvent: MessageEvent) {
if (messageEvent.path == "/command") {
val message = String(messageEvent.data)
val messageIntent = Intent()
messageIntent.action = Intent.ACTION_SEND
messageIntent.putExtra("message", message)
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent)
} else {
super.onMessageReceived(messageEvent)
}
}
}
Edit:
I register the receiver in onCreate using
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter())
Thank you for helping me!
You've registered your BroadcastReceiver with an empty IntentFilter.
When you register your BroadcastReceiver, you need to provide an IntentFilter that tells Android what broadcast Intents should be delivered to your BroadcastReceiver. Since your Service is sending a broadcast Intent with ACTION_SEND, you can set up an IntentFilter that will trigger on ACTION_SEND, like this:
LocalBroadcastManager.getInstance(this)
.registerReceiver(broadcastReceiver, IntentFilter(Intent.ACTION_SEND))
Installing App Manually
val install = Intent(Intent.ACTION_VIEW)
install.setDataAndType(
uri,
APP_INSTALL_PATH
)
// install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
}
startActivity(install)
Handling Broadcast Receiver
val intentFilter = IntentFilter()
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)
intentFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL)
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED)
intentFilter.addAction(Intent.ACTION_MY_PACKAGE_REPLACED)
intentFilter.addDataScheme("package")
registerReceiver(restartAppReceiver, intentFilter)
private val restartAppReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(this#LoginActivity, getString(R.string.sign_out), Toast.LENGTH_LONG)
.show()
//start activity
val i = Intent()
Log.i("App_started", "Yes")
i.setClassName(packageName, packageName+".screen.activity.LoginActivity")
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context?.startActivity(i)
}
}
Problem Facing
Here I'm not able to receive anything on receiver when app gets installed manually. I need to open the app automatically when it gets installed manually without any action from users end.
thats simple: you can't. user must open it manually. starting Android 10 you can't start any Activity from BroadcastReceiver. besides that: most of your IntentFilter entries are no-op (why are you calling addDataScheme)
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.
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
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