Change context of intent android - android

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"

Related

Save image using kotlin

I am new to Android development, and im making simple aplication that capture image then save. I can capture the image and show into imageview, but unfortunately i cannot save into gallery.
i tryed many ways but cannot save. this is original code to take and show.
// EDITED //
I add function to save file, but still not working
class TomarFotos : AppCompatActivity() {
lateinit var photoPath: String
val REQUEST_IMAGE_CAPTURE = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tomar_fotos)
val foto = findViewById<Button>(R.id.tomarfotos)
foto.setOnClickListener{
tomarFoto()
}
}
fun tomarFoto() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(intent.resolveActivity(packageManager) != null){
var photoFile: File? = null
try{
photoFile = createImageFile()
}catch (e: IOException){}
if(photoFile != null){
val photoUri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
photoFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fotoTomada = findViewById<ImageView>(R.id.fotopreview)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
fotoTomada.rotation = 90f
fotoTomada.setImageURI(Uri.parse(photoPath))
}
}
private fun createImageFile(): File? {
val fileName = "foto"
val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
fileName,
".jpg",
storageDir
)
photoPath = image.absolutePath
return image
}
}
i try developer.android.com already but didnt work
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val fotoTomada = findViewById<ImageView>(R.id.fotopreview)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data?.extras?.get("data") as Bitmap
fotoTomada.setImageBitmap(imageBitmap)
saveImage(imageBitmap)
}
}
Call this function to save image to gallery
private fun saveImage(bitmap: Bitmap) {
var outStream: FileOutputStream? = null
// Write to SD Card
try {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "AppName/")
dir.mkdirs()
val fileName = "IMG_${System.currentTimeMillis()}"
val outFile = File(dir, fileName)
outStream = FileOutputStream(outFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
Toast.makeText(this#MainActivity, "Image Saved Successfully", Toast.LENGTH_LONG).show()
} catch (e: FileNotFoundException) {
Log.d("TAG", "saveImage: ${e.message}")
} catch (e: IOException) {
Log.d("TAG", "saveImage: ${e.message}")
}
}

Unable to capture image in android 11

i'm trying to capture image in android 11 device but request is keep cancelled. i have added also. still unable to capture image. pick image from gallery is working. image is not storing in Android/data folder.
i have added val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) also still unable to create temp file in storage. please provide any solutions
private fun selectImage() {
imageUtils.createImageFile(applicationContext).let {
viewModel.setFileTempPath(it.absolutePath, "doc_name")
startActivityForResult(imageUtils.captureImage(applicationContext, it), 300)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
300 -> when (resultCode) {
RESULT_OK -> {
Log.d("tmppath", data?.data.toString())
if (data != null && data.data != null) {
val selectedImage: Bitmap =
imageUtils.getBitmap(data.data, this#TaggingActivity)!!
viewModel.dataModel.selectedImagesArrayList.value.let {
if (it == null) {
viewModel.dataModel.selectedImagesArrayList.value = ArrayList()
}
val a = it
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
}
} else {
if (viewModel.dataModel.tmpPath.value != null) {
imageUtils.getBitmapFromPath(viewModel.dataModel.tmpPath.value)
?.let { selectedImage ->
val a = viewModel.dataModel.selectedImagesArrayList.value
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
} ?: run {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
}
} else {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
return
}
}
viewModel.dataModel.tmpPath.value = null
}
RESULT_CANCELED -> {
viewModel.setFileTempPath("", "")
Toast.makeText(this,"cancelled",Toast.LENGTH_LONG).show()
}
}
}
//Intent class
fun getCameraIntent(file: File): Intent {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
if (Build.VERSION.SDK_INT >= 24) {
try {
val m =
StrictMode::class.java.getMethod("disableDeathOnFileUriExposure")
m.invoke(null)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
} else {
takePictureIntent.putExtra("return-data", true)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
val intents: ArrayList<Intent> = arrayListOf()
intents.add(takePictureIntent)
intents.add(pickPhoto)
val chooserIntent = Intent.createChooser(
intents.removeAt(intents.size - 1),
" Document Upload"
)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(arrayOf<Parcelable>()))
return chooserIntent
}

Put intent to sharedPreferences return ""

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?

Unable to update the UI using Broadcast Receiver(Kotlin)

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))
}
}

onActivityResult is not called (Kotlin)

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)
}

Categories

Resources