Is there a way to make a customView for battery? - android

Is there a way to make a customView for the battery status?
Like i'm trying to make a kiosk app so the status bar is hided and i'm showing the wi-fi status with the following library, is there a way to make something for the battery or is there yet an existing library for it?

Just register broadcast receiver and get what you need in onReceive
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val battery = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
}
//todo
}
registerReceiver(receiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))

Related

check if bluetooth is connected to any device with broadcast receiver

I need to check if the device is connected to any device via Bluetooth.
This is my activity where I launch activity for Bluetooth settings. ``
receiver = BluetoothModeReceiver()
IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED).also {
registerReceiver(receiver, it)
val settingsIntent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
startActivity(settingsIntent)
}
And this is the broadcast receiver:
class BluetoothModeReceiver :BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val isDeviceConnected = intent?.getBooleanExtra("state",false) ?: return
if(isDeviceConnected){
Log.i("Broadcast", "Happened ")
}
}
}
I also tried to use intents like BluetoothDevice.ACTION_ACL_CONNECTED and ACTION_ACL_DISCONNECTED but none of them work. When I connect the phone to any device that log in receiver doesn't get printed in the logcat. Any ideas why it doesn't work? They would be appreciated.

Android Kotlin Broad Receiever in RecyclerAdapter Won't Communicate to Broadcast Receiever in MainActivity

Context: No receiver is declared in the manifest since I am not declaring a new receiver.
I am a bit confused about why the receiver in MainActivity does not receieve the broadcast sent from the recycler adapter.
RecyclerAdapter
holder.checkBox.setOnClickListener {view ->
item.completed = holder.checkBox.isChecked
Log.i("wow", "is checked: ${holder.checkBox.isChecked}")
val intent = Intent().apply {
addCategory(Intent.CATEGORY_DEFAULT)
setAction(changeCompletedForDeck)
putExtra(changeCompletedForDeckItemID, item)
}
LocalBroadcastManager.getInstance(view.context).sendBroadcast(intent)
MainActivity
private lateinit var broadcastReceiver: BroadcastReceiver
broadcastReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
//get deck, if deck != null then update the checkmark response
if (intent?.action == DeckRecyclerAdapter.changeCompletedForDeck) {
val deck = intent?.extras?.getParcelable<Deck>(DeckRecyclerAdapter.changeCompletedForDeckItemID)
Log.i("wow", "${deck?.title}")
deck?.let { deck ->
globalViewModel.update(deck)
}
}
}
}
val filter = IntentFilter(DeckRecyclerAdapter.changeCompletedForDeck)
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter)
//Destroy the BroadcastReceiver
override fun onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
super.onDestroy()
}
Your problem is Intent action . See at the time of register you have not provided any action so receiver will not be identified by the system.
You can define a specific action with IntentFilter and use the same action during register and sendBroadcast.
To identify different conditions you can do two things.
you can set data in Bundle and validate the bundle value inside onReceive()
you can also add multiple actions to IntentFilter and validate the action inside onReceive() See this.
So with the first way have a constant action in MainActivity:-
companion object{
const val BROADCAST_ACTION="LIST_CHECK_ACTION"
}
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, IntentFilter(BROADCAST_ACTION)).
Then for sending broadcast use the code below addCategory(Intent.CATEGORY_DEFAULT) is not required:-
val intent = Intent().apply {
action = MainAcvity.BROADCAST_ACTION
putExtra("item", item)
}
LocalBroadcastManager.getInstance(view.context).sendBroadcast(intent)
PS- However i don't think you should be using a Broadcastreceiver just to provide a callback from Adapter its purpose is more than that. You should be using a callback listener for it . Since RecyclerView.Adapter will binds to a UI component a callback interface will be fine . I think a broadcastReceiver is overkill in this usecase .

Start activity from receiver in Android Q

I'm checking my app with the Android Q [beta 6] in order to add all the required changes to be fully-compatible with the last SO. However, I found out that I am using a Receiver to start an Activity from background and due to the last background limitations implemented (https://developer.android.com/preview/privacy/background-activity-starts) the activity is not being opened.
I tried to use both the receiver context and application context to start the activity but in both cases the system shows a toast saying that is not possible to start activity from background.
What I tried on the Receiver...
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
context?.applicationContext?.let {
it.startActivity(Intent(it, MyActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
PushUtils.showReceiverCalledNotification(it)
}
}
That way I wanted to start MyActivity and also show a notification when the receiver is called. Instead, I can see the notification but the Activity is never started. It is very important for the feature to start the activity immediately, so there is a way to continue starting the activity from the receiver?
It is very important for the feature to start the activity immediately, so there is a way to continue starting the activity from the receiver?
No, sorry. Use a high-priority notification, so it appears in "heads-up" mode. The user can then rapidly tap on it to bring up your activity.
Due to restrictions, you cannot start activity from background. Instead you can use notifications as CommonsWare suggested and also suggested on the android developer site.
Here's the official documentation that lists situations when it will work and when won't.
https://developer.android.com/guide/components/activities/background-starts
You can use something like this:
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
context ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
showNotification(context.applicationContext)
} else {
context.applicationContext.startActivity(Intent(context, MyActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
}
PushUtils.showReceiverCalledNotification(context)
}
private fun showNotification(context: Context) {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("default", "default", NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
val intent = Intent(context, MyActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
with(NotificationCompat.Builder(context, "default")) {
setSmallIcon(R.drawable.ic_scan_colored)
setContentTitle("Custom Title")
setContentText("Tap to start the application")
setContentIntent(pendingIntent)
setAutoCancel(true)
manager.notify(87, build())
}
}
}

Kotlin: Call a function to update UI from BroadcastReceiver onReceive

I am new to Kotlin, and it seems awesome! Though today, I've been trying to do something that in Java was super simple, but I've got totally stuck.
I am using a broadcast receiver to determine when the device is connected/ disconnected from a power source. And all I need to do it update my UI accordingly.
My Code
Here's my BroadcastReceiver classs, and it seems to work fine.
class PlugInReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action == Intent.ACTION_POWER_CONNECTED) {
// Do stuff when power connected
}
else if (action == Intent.ACTION_POWER_DISCONNECTED) {
// Do more stuff when power disconnected
}
}
}
Now in my MainActivity (but somewhere else, later on), I want to update my UI when the intent is fired, for example in the function below, the background color changes.
private fun updateBackgroundColor( newBgColorId: Int = R.color.colorAccent){
val mainLayout = findViewById<View>(R.id.mainLayout)
val colorFade = ObjectAnimator.ofObject(
mainLayout, "backgroundColor", ArgbEvaluator(), oldBgColor, newBgColor)
colorFade.start()
}
The Question
How can I call a function on the MainActivity, or update my UI when the BroadcastReceiver fires an event?
What I've tried so far
I looked into having a static variable somewhere, storing the result of the BroadcastReciever, then an observable in my UI class, watching and calling appropriate function accordingly. Though after Googling how to do this, looks like that's not really a good approach in Kotlin.
Considered trying to run the BroadcastReciever on the UI thread, but that sounds like a terrible idea.
Tried mixing a Java implementation with my Kotlin class, but couldn't get it to work.
Frustratingly I found several very similar questions on SO. However their implementations seem to all use Java-specific features:
Android BroadcastReceiver onReceive Update TextView in MainActivity
How to update UI in a BroadcastReceiver
Calling a Activity method from BroadcastReceiver in Android
How to update UI from BroadcastReceiver after screenshot
I'm sure this is a trivial question for most Android developers, but I am lost! Let me know if you need any more details. Thanks very much in advance!
Sharing the info to register BroadcastReceiver in Kotlin
Step 1. Create BroadcastReceiver in MainActivity.kt
private val mPlugInReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
Intent.ACTION_POWER_CONNECTED -> {
//update your main background color
updateBackgroundColor()
}
Intent.ACTION_POWER_DISCONNECTED -> {
//update your main background color
updateBackgroundColor()
}
}
}
}
Step 2. Create IntentFilter
private fun getIntentFilter(): IntentFilter {
val iFilter = IntentFilter()
iFilter.addAction(Intent.ACTION_POWER_CONNECTED)
iFilter.addAction(Intent.ACTION_POWER_DISCONNECTED)
return iFilter
}
Step 3. Register receiver at onStart()
override fun onStart() {
super.onStart()
registerReceiver(mPlugInReceiver, getIntentFilter())
}
Step 4. Unregister receiver at onStop()
override fun onStop() {
super.onStop()
unregisterReceiver(mPlugInReceiver)
}
If you have custom BroadcastReceiver, you can register using LocalBroadcastManager and create your local IntentFilter
private val mLocalBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
AnyService.UPDATE_ANY -> {
}
}
}
}
private fun getLocalIntentFilter(): IntentFilter {
val iFilter = IntentFilter()
iFilter.addAction(AnyService.UPDATE_ANY)
return iFilter
}
Register local receiver
LocalBroadcastManager.getInstance(applicationContext).registerReceiver(mLocalBroadcastReceiver, getLocalIntentFilter())
Unregister local receiver LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(mLocalBroadcastReceiver)
The best way to achieve that is to create an abstract method in the BroadcastReceiver, and when onReceive() method is called, you can invoke that method that will be implemented by your activity.
BroadcastReceiver example:
abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
//Do the checks or whatever you want
var isConnected = true
broadcastResult(isConnected)
}
protected abstract fun broadcastResult(connected: Boolean)
}
And the code in your activity (in the onCreate or onStart for example). Here you register the broadcast receiver with the method implementation, and here you can update the UI:
var connectionBroadcastReceiver = object : ConnectionBroadcastReceiver() {
override fun broadcastResult(connected: Boolean) {
if(isConnected){
refreshList()
}
}
}
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
this.registerReceiver(connectionBroadcastReceiver, intentFilter)
Don't forget to unregister the receiver in (onPause||onStop||onDestroy), but it's not strictly necessary.
The onReceive(...) method runs on the main thread. You can register your Activity in onStart() and unregister it in onStop(), which will guarantee that your UI is present when the event is received.

Broadcast Receiver in Application class android

I am registering BroadcastReceiver in application class and its register method is getting called and completed successfully without issue during application start. I am sending a broadcast from the module. I can print the action, it is there. But the app is not catching the broadcast. I don't know where I am doing wrong.
Below is the method to register receiver.
fun registerRecordingDataReceiver () {
info("AppReceiver register called=>${CommonsDataVars.TEMPERATURE.action()}")
val temperatureCompleted = CommonsDataVars.TEMPERATURE.action()
val temperatureCompletedIntentFilter = IntentFilter(temperatureCompleted)
val broadcastManager = LocalBroadcastManager.getInstance(this)
broadcastManager.registerReceiver(appReceiver,temperatureCompletedIntentFilter)
info("AppREceiver register completed")
}
Part of Broadcast Receiver
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.getAction()
debug("Action in App Receiver =>"+action)
if (action == CommonsDataVars.TEMPERATURE.action()) {
info("AppReceiver****************************************")
sendBroadcast part:
info("TEMPERATURE register called=>${CommonsDataVars.TEMPERATURE.action()}")
val intent = Intent()
intent.setAction(CommonsDataVars.TEMPERATURE.action())
//intent.putExtra(CommonsDataVars.TEMPERATURE.name, temperatureData)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

Categories

Resources