I wanted to update the UI of My MainActivity when the bluetooth is On/Off
MainActivity
private val broadcastReceiver = Broadcast()
open var bluetooth : ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
registerReceiver(broadcastReceiver, filter)
val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
bluetooth = findViewById(R.id.image_bluetooth)
val bluetoothName = findViewById<TextView>(R.id.text_bluetooth_name)
bluetoothName.text = bluetoothAdapter.name
bluetooth?.setOnClickListener {
if (!bluetoothAdapter.isEnabled) {
val turnOn = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(turnOn, 0)
} else {
bluetoothAdapter.disable()
}
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(broadcastReceiver)
}
fun enableBluetooth()
{
bluetooth?.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_bluetooth_enable_48dp))
}
fun disableBluetooth()
{
bluetooth?.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_bluetooth_disable_48dp))
}
BroadcastReceiver
class Broadcast : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action
val mainActivity = MainActivity()
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
when (intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
BluetoothAdapter.STATE_OFF -> {
Toast.makeText(context, "Bluetooth Turned OFF", Toast.LENGTH_LONG).show()
mainActivity.disableBluetooth()
}
BluetoothAdapter.STATE_ON -> {
Toast.makeText(context, "Bluetooth Turned ON", Toast.LENGTH_LONG).show()
mainActivity.enableBluetooth()
}
}
}
}
}
After the onReceive call in BroadcastReceiver, in enableBluetooth and disableBluetooth method bluetooth value return null.Can any one help to over come the process?Thanks in advance
For this case, use On onActivityResult Method to update the UI
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && bluetoothAdapter!!.isEnabled) {
Toast.makeText(this, "Bluetooth Turned ON", Toast.LENGTH_LONG).show()
image_bluetooth?.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_bluetooth_enable_48dp))
}
}
Related
The below code is Working for Android 12 but same not working Android 10 the problem its it showing the run time permission pop up for BLUETOOTH_CONNECT
Here is the below code i have written inside the fragment
class FirstFragment : Fragment() {
private var _binding: FragmentFirstBinding? = null
private var ctx: Context? = null
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
companion object {
private const val BLUETOOTH_PERMISSION_CODE = 100
private const val BLUETOOTH_CONNECT_PERMISSION_CODE = 101
}
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentFirstBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.ctx = view.context
//get the devie manifrature name
System.out.println(android.os.Build.MANUFACTURER)
//get the type of the bluetooth device
getBluetoothDeviceType()
checkPermission(
Manifest.permission.BLUETOOTH_CONNECT,
BLUETOOTH_CONNECT_PERMISSION_CODE
)
binding.buttonFirst.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
private fun requestBluetoothPermission() {
}
private fun getBluetoothDeviceType() {
if (ActivityCompat.checkSelfPermission(
ctx!!,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {
if (BluetoothClass.Device.PHONE_CELLULAR == 0x0204) {
System.out.println("permission is granted")
}
} else {
if (BluetoothClass.Device.PHONE_CELLULAR != 0x0204) {
System.out.println("permission is not granted")
}
}
}
private fun checkPermission(permission: String, requestCode: Int) {
if (ContextCompat.checkSelfPermission(
ctx!! as Activity,
permission
) != PackageManager.PERMISSION_GRANTED
) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
println("permission is not required")
} else {
requestPermissions(arrayOf(permission), requestCode)
}
// Requesting the permission
//Fragment.requestPermission.launch(Manifest.permission.CAMERA)
} else {
Toast.makeText(ctx!! as Activity, "Permission already granted", Toast.LENGTH_SHORT)
.show()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == BLUETOOTH_CONNECT_PERMISSION_CODE) {
//permission granted
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (bluetoothAdapter == null) {
// Handle the situation where Bluetooth is not available
} else {
// Get a set of currently paired devices
if (ContextCompat.checkSelfPermission(
ctx!! as Activity,
permissions[0]
) == PackageManager.PERMISSION_GRANTED
) {
val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices
// If there are paired devices
if (pairedDevices.isNotEmpty()) {
// Loop through paired devices
for (device in pairedDevices) {
// Check if the device is a scanner
if (device.bluetoothClass.majorDeviceClass == BluetoothClass.Device.Major.IMAGING) {
// Device is a scanner
val scannerDevice = device
println("Scanner found: ${scannerDevice.name}")
}
}
} else {
// Handle the situation where there are no paired devices
}
}
Toast.makeText(
ctx!! as Activity,
"Bluetooth Connect Permission Granted",
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(
ctx!! as Activity,
"Bluetooth Connect Permission Denied",
Toast.LENGTH_SHORT
).show()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
here how below my build.gradle looks like
android {
compileSdk 33
defaultConfig {
applicationId "com.demo"
minSdk 23
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
I have a service start with:
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
if (requestCode == com.robertohuertas.endless.MainActivity.REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val intentx:Intent =ScreenCaptureService.getStartIntent(this,resultCode,data)
startService(intentx)
when phone reboot i will restart serive. i saved intent in sharedPreferences. But when phone after reboot context is different,now i get intent as code(intentx):
class StartReceiver : BroadcastReceiver() {
private val PREFS_KEY_intent = "myPreferncesintent"
private val PASSWORD_KEY_intent = "myPreferncesintent"
var intentx: Intent? =null
#RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
val sharedPreferences: SharedPreferences =
context.getSharedPreferences(PREFS_KEY_intent, Context.MODE_PRIVATE)
val key= sharedPreferences.getString(PASSWORD_KEY_intent, "")
try {
intentx= Intent.parseUri(key, 0)
} catch (e: URISyntaxException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
in short Example :Intent intent = new Intent(context, com.robertohuertas.endless.ScreenCaptureService.class); How to change context in this "intent"
Hello I have a mediaproject service. I start it with startActivityForResult
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
if (requestCode == com.robertohuertas.endless.MainActivity.REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val bundle = data?.extras
if (bundle != null) {
for (key in bundle.keySet()) {
Log.d("TAGTAGTAGTAGTAGTA_st", key + " : " + if (bundle[key] != null) bundle[key] else "NULL")
}
}
// GlobalConstant.datax=data;
val sharedPreferences = getSharedPreferences(
PREFS_KEY_intent, MODE_PRIVATE
)
val editor = sharedPreferences.edit()
val uriString: String = data!!.toUri(requestCode)
editor.putString(PASSWORD_KEY_intent, uriString)
editor.commit()
Log.d("main_asssssssss","bolssss "+uriString)
startService(
com.robertohuertas.endless.ScreenCaptureService.getStartIntent(
this,
resultCode,
data
)
)
}
}
}
I want to save intent and use it after phone reboot but i can't get in onActivityResult
The result of Log.d("TAGTAGTAGTAGTAGTA_st" is android.media.projection.extra.EXTRA_MEDIA_PROJECTION : android.os.BinderProxy#6bb5fa5
,but result of Log.d("main_asssssssss","bolssss "+uriString) is D/main_asssssssss: bolssss don't have see uriString,it is "". where is my wrong?
NEW
I try as #muhammad-shuja this code:
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
val intentx:Intent=ScreenCaptureService.getStartIntent(this,resultCode,data)
ScreenCaptureService.getStartIntent is:
public static Intent getStartIntent(Context context, int resultCode, Intent data) {
Intent intent = new Intent(context, com.robertohuertas.endless.ScreenCaptureService.class);
intent.putExtra("ACTION", START);
intent.putExtra("RESULT_CODE", resultCode);
intent.putExtra("DATA", data);
return intent;
}
I saved value intentx.getExtras()?.getString("DATA") to sharedPreferences
val editor = sharedPreferences.edit()
val xsd=intentx.getExtras()?.getString("DATA")
editor.putString(PASSWORD_KEY_intent, xsd)
editor.commit()
BroadcastReceiver
class StartReceiver : BroadcastReceiver() {
private val PREFS_KEY_intent = "myPreferncesintent"
private val PASSWORD_KEY_intent = "myPreferncesintent"
var telApp: Intent? =null
#RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
// Toast.makeText(
// this#StartReceiver,
// "Tải mô hình không thành công onOrientationChanged!",
// Toast.LENGTH_SHORT
// ).show()
if (intent.action == Intent.ACTION_BOOT_COMPLETED && getServiceState(context) == ServiceState.STARTED) {
val sharedPreferences: SharedPreferences =
context.getSharedPreferences(PREFS_KEY_intent, Context.MODE_PRIVATE)
val password = sharedPreferences.getString(PASSWORD_KEY_intent, "")
try {
telApp = Intent.parseUri(password, 0)
} catch (e: URISyntaxException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
if (telApp!=null){
val audioCaptureIntent22=com.robertohuertas.endless.ScreenCaptureService.getStartIntent(
context,
Activity.RESULT_OK,
telApp
)
context.startService(audioCaptureIntent22)}
}
where am i wrong?
I need to use Location in my application and I check location at every onResume. When location is switched off I try to switch it on with:
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!LocationManagerCompat.isLocationEnabled(lm)) {
val intent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
return
}
When this activity finished my application exited. I tried startActivityForResult, but it didn't help. How can I return to my application after settings?
thx
Zamek
override fun onResume() {
super.onResume()
checkLocation()
}
private fun checkLocation() {
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(LocationRequest().apply {
interval = 10000
fastestInterval=5000
priority=LocationRequest.PRIORITY_LOW_POWER
})
val settingsClient = LocationServices.getSettingsClient(this)
val task : Task<LocationSettingsResponse> = settingsClient.checkLocationSettings(builder.build())
task.addOnSuccessListener {
model.start()
}
task.addOnFailureListener{
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), REQUEST_LOCATION)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
when(requestCode) {
REQUEST_LOCATION -> locationResult(grantResults)
}
}
private fun locationResult(grantResults: IntArray) {
if (grantResults[0]==PackageManager.PERMISSION_GRANTED) {
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!LocationManagerCompat.isLocationEnabled(lm)) {
val intent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
return
}
model.start()
return
}
exitApplication()
}
I checked it on a Xiaomi device. Maybe that should be the problem...
thx,
Zamek
I need help. On my onCreate() I have this code:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
Log.v("ProjectDetails", "onTakeFromGallery called")
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }
An on my onActivityResult, I wrote:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PICK_IMAGE -> {
Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
val inputStream = contentResolver.openInputStream(data.data)
val bitMap = BitmapFactory.decodeStream(inputStream)
projectDetails_image.setImageBitmap(bitMap)
// TODO Save image URI to database
} catch (e: Exception) {
Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
}
} else {
Log.v("ProjectDetails", "data is null")
}
}
}
}
}
The problem is, onActivityResult() doesn't fire when an image is selected. What should I do?
Solved it! The solution is to put the codes inside my onTakeGallery() function to a function that belongs to the Activity class. So my code will look like this:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
dispatchSelectFromGalleryIntent()
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener {
takePhotoDialog?.show(supportFragmentManager)
}
And the extracted codes goes here:
private fun dispatchSelectFromGalleryIntent() {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}