I need to scan for a list of wifi access points in my android app. I've done it in the past using java, but I'm having trouble getting my kotlin code to work.
My code:
var resultList = ArrayList<ScanResult>()
lateinit var wifiManager: WifiManager
val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
resultList = wifiManager.scanResults as ArrayList<ScanResult>
Log.d("TESTING", "onReceive Called")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
wifiManager = this.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
}
override fun onGridTileClicked(x: Int, y: Int) {
startScanning()
}
fun startScanning() {
registerReceiver(broadcastReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
Handler().postDelayed({
stopScanning()
}, 10000)
}
fun stopScanning() {
unregisterReceiver(broadcastReceiver)
val axisList = ArrayList<Axis>()
for (result in resultList) {
axisList.add(Axis(result.BSSID, result.level))
}
Log.d("TESTING", axisList.toString())
}
The onReceive() function is never called, and I have the ACCESS_FINE_LOCATION and ACCESS_WIFI_STATE both declared in the manifest, so I'm not sure what I'm doing wrong. I'm sure I'm missing something obvious, but some help would be appreciated. Thanks!
You forgot to start scanning. Add wifiManager.startScan() call in your startScanning method.
Related
Integrating Jitsi Sample in my project. but meeting unable to establish getting Cannot join, view is null error in logs. can anyone suggest what could be the issue?
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
onBroadcastReceived(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val serverURL: URL = try {
URL("https://meet.jit.si")
} catch (e: MalformedURLException) {
e.printStackTrace()
throw RuntimeException("Invalid server URL!")
}
val defaultOptions = JitsiMeetConferenceOptions.Builder()
.setServerURL(serverURL)
// When using JaaS, set the obtained JWT here
//.setToken("MyJWT")
// Different features flags can be set
//.setFeatureFlag("toolbox.enabled", false)
//.setFeatureFlag("filmstrip.enabled", false)
.setFeatureFlag("welcomepage.enabled", false)
.build()
JitsiMeet.setDefaultConferenceOptions(defaultOptions)
registerForBroadcastMessages()
binding.button4.setOnClickListener{
onButtonClick()
}
}
override fun onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
super.onDestroy()
}
private fun onButtonClick() {
val text = binding.conferenceName.text.toString()
if (text.isNotEmpty()) {
// Build options object for joining the conference. The SDK will merge the default
// one we set earlier and this one when joining.
val options = JitsiMeetConferenceOptions.Builder()
.setRoom(text)
// Settings for audio and video
//.setAudioMuted(true)
//.setVideoMuted(true)
.build()
// Launch the new activity with the given options. The launch() method takes care
// of creating the required Intent and passing the options.
JitsiMeetActivity.launch(this, options)
}
}
private fun registerForBroadcastMessages() {
val intentFilter = IntentFilter()
/* This registers for every possible event sent from JitsiMeetSDK
If only some of the events are needed, the for loop can be replaced
with individual statements:
ex: intentFilter.addAction(BroadcastEvent.Type.AUDIO_MUTED_CHANGED.action);
intentFilter.addAction(BroadcastEvent.Type.CONFERENCE_TERMINATED.action);
... other events
*/
for (type in BroadcastEvent.Type.values()) {
intentFilter.addAction(type.action)
}
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter)
}
// Example for handling different JitsiMeetSDK events
private fun onBroadcastReceived(intent: Intent?) {
if (intent != null) {
val event = BroadcastEvent(intent)
when (event.type) {
BroadcastEvent.Type.CONFERENCE_JOINED -> Timber.i("Conference Joined with url%s", event.getData().get("url"))
BroadcastEvent.Type.PARTICIPANT_JOINED -> Timber.i("Participant joined%s", event.getData().get("name"))
else -> Timber.i("Received event: %s", event.type)
}
}
}
// Example for sending actions to JitsiMeetSDK
private fun hangUp() {
val hangupBroadcastIntent: Intent = BroadcastIntentHelper.buildHangUpIntent()
LocalBroadcastManager.getInstance(this.applicationContext).sendBroadcast(hangupBroadcastIntent)
}
}
added below dependency.
dependencies {
// Jitsi Meet
implementation "org.jitsi.react:jitsi-meet-sdk:5.1.0"
}
Sharing log information also. this sample I am integrating into kotlin multiplatform project.
please suggest to resolve this issue.
Im trying to set a continuos broadcast from Kotlin to dart using an EventChannel, following this example: GITHUB REPO it uses an IntentFilter in order to notify the battery status.
What im trying to do is to return each second if possible a value that's stored on a sharedPreference, but it doesn't matter if I set the Intent to stream with action_send, flutter doesn't receive the value.
this is the current code.
private lateinit var streamChannel: EventChannel
private lateinit var statusValueStateChangeReceiver: BroadcastReceiver
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
streamChannel = EventChannel(
flutterEngine.dartExecutor.binaryMessenger, "continuous.stream.boolean/statusValue")
streamChannel.setStreamHandler(this)
}
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
statusValueStateChangeReceiver = createStatusValueStateChangeReceiver(events);
applicationContext.registerReceiver(
statusValueStateChangeReceiver, IntentFilter(Intent.ACTION_SEND));
}
override fun onCancel(arguments: Any?) {
applicationContext.unregisterReceiver(statusValueStateChangeReceiver);
}
private fun createStatusValueStateChangeReceiver(events: EventChannel.EventSink?): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
events?.success(intent?.let { MyClass().getStatusValue() })
}
}
}
how can I keep sending the data to dart in a persistent way? thanks in advance.
Im implementing a simple blutooth classic scan from the official docs on my Redmi Note 4 (Bluetooth 4.1).
However I am not seeing a toast that should appear when the onReceive function on the broadcast receiver is called.
What could be wrong here?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
defaultAdapter = BluetoothAdapter.getDefaultAdapter()
if (defaultAdapter == null) {
toast("no adapter")
return
}
if (!defaultAdapter!!.isEnabled) {
val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
}
searchButton.setOnClickListener { newDevicesList() }
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
Log.i("receiver", "registering receiver")
registerReceiver(receiver, filter)
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
toast("maybe i find new device who know")
when (intent.action) {
BluetoothDevice.ACTION_FOUND -> {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
val device: BluetoothDevice? =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device?.name
val deviceHardwareAddress = device?.address // MAC address
toast("device $deviceName was found")
}
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
context.unregisterReceiver(this)
}
}
if (defaultAdapter!!.isDiscovering) {
toast("scan already in progress")
} else {
toast("starting discovery")
defaultAdapter!!.startDiscovery();
}
}
How do i know that the onReceive function never gets called? cause this toast toast("maybe i find new device who know") never appears.
I use Broadcast to listen network changed, when I registered network changed broadcast, then I receive the notification in broadcast's onReceive() method by launch app firstly, it shows the network has a connection, but my phone's network not changed, It has always network connection.
private val mNetWorkChangeReceiver = NetWorkChangeReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
register()
}
private fun register() {
val intentFilter = IntentFilter()
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
registerReceiver(mNetWorkChangeReceiver, intentFilter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(mNetWorkChangeReceiver)
}
class NetWorkChangeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("test", "intent action = ${intent!!.action}")
}
}
I don't know how should I modify?
I have a small bluetooth project in kotlin. The code for it is below:
var mArrayAdapter: ArrayAdapter<String>? = null
val bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
var myList: MutableList<String> = mutableListOf<String>()
var devices = ArrayList<BluetoothDevice>()
var devicesMap = HashMap<String, BluetoothDevice>()
class MainActivity : AppCompatActivity(), View.OnClickListener {
private val REQUEST_ENABLE_BT = 1000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.btn_scan).setOnClickListener(this)
checkBluetoothStatus()
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(receiver, filter)
mArrayAdapter = ArrayAdapter(this, R.layout.dialog_select_device)
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String? = intent.action
when(action) {
BluetoothDevice.ACTION_FOUND -> {
val device: BluetoothDevice =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device.name
myList.add(deviceName)
}
}
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.btn_scan ->
startScan()
}
}
fun startScan() {
if (BluetoothAdapter.getDefaultAdapter().startDiscovery()) {
val myToast = Toast.makeText(this, myList.toString(), Toast.LENGTH_SHORT)
myToast.show()
}
}
}
When a user clicks a button, I want to be able to see a list of other bluetooth devices (which I thought the onReceive method would enable me to do). So I'm adding device names to the myList variable, which I'm then displaying in a toast. But at the moment when they click, nothing comes up. Grateful for your advice.