I'm just setting out with teaching myself about Android audio development, and I'm rather baffled as to why neither the onConnected nor the onConnectionFailed method of connectionCallback is called here. PodcastService is instantiated and its onGetRoot method is called, but the callback is not called. No error messages are given; the callback is simply not called. Any help would be great!
MainActivity.kt:
package com.davidwillett.audioapp
import android.content.ComponentName
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
class MainActivity : AppCompatActivity() {
private val connectionCallback = object : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
println("ConnectionCallback.onConnected")
super.onConnected()
}
override fun onConnectionFailed() {
println("ConnectionCallback.onConnectionFailed")
super.onConnectionFailed()
}
}
private lateinit var mediaBrowser: MediaBrowserCompat
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mediaBrowser = MediaBrowserCompat(
this,
ComponentName(this, PodcastService::class.java),
connectionCallback,
null)
}
override fun onStart() {
println("MainActivity.onStart")
super.onStart()
mediaBrowser.connect()
}
override fun onStop() {
println("MainActivity.onStop")
super.onStop()
mediaBrowser.disconnect()
}
}
PodcastService.kt:
package com.davidwillett.audioapp
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import androidx.media.MediaBrowserServiceCompat
class PodcastService : MediaBrowserServiceCompat() {
override fun onGetRoot(
clientPackageName: String,
clientUid: Int,
rootHints: Bundle?
): BrowserRoot? {
println("PodcastService.onGetRoot")
return BrowserRoot("root", null)
}
override fun onLoadChildren(
parentId: String,
result: Result<MutableList<MediaBrowserCompat.MediaItem>>
) {
TODO("Not yet implemented")
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.davidwillett.audioapp">
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".PodcastService"
android:exported="false">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
</application>
</manifest>
Sorry, I didn't do my research well enough!
A comment in the UAMP demo project states that: "In order for MediaBrowserCompat.ConnectionCallback.onConnected to be called, a MediaSessionCompat.Token needs to be set on the MediaBrowserServiceCompat."
So that'll be what's missing!
Related
I have two activities, QuizQuestions, and MainActivity2. When I set up QuizQuestions in the Manifest intent filter the app opens and launches fine. However when I set up my app to open with MainActivity2 it fails to initialize at all. I have looked at the files side by side and I cannot find what the difference in them is to see why one would launch and the other wont.
I am brand new to Kotlin so I am sure it is something very obvious that I am missing. Any help is greatly appreciated.
Thank you.
Here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.crazywkids.officequiz">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.OfficeQuiz">
<activity
android:name=".QuizQuestions"
android:exported="true"
/>
<activity
android:name=".MainActivity2"
android:exported="true"
android:theme="#style/NoActionBarTheme"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here is MainActivity2
package com.crazywkids.officequiz
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val beginBtn = findViewById<Button>(R.id.beginBtn)
beginBtn.setOnClickListener {
val intent = Intent(this, QuizQuestions::class.java)
startActivity(intent)
}
}
}
Here is QuizQuestions
package com.crazywkids.officequiz
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class QuizQuestions : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
val question=Constants.getQuestions()
Log.i("Question Size", "${question.size}")
}
}
I have already searched for the problem that my huawei p30 lite doesn't discover other bluetooth devices. I tried it with an onther device and it worked but I don't get it why it doesn't work on my huawei p30 lite.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notfallapp">
<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/notfallapplogo"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.DayNight.NoActionBar">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".menubar.MapActivity"
android:label="#string/title_activity_map"></activity>
<activity
android:name=".Login.LoginActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".Login.SignUpActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".menubar.contact.ContactActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".menubar.contact.AddContactActivity"
android:screenOrientation="portrait" />
<activity
android:name=".menubar.AlarmsActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".menubar.SettingsActivity"
android:screenOrientation="portrait"></activity>
<activity
android:name=".alarm.CallAlarmActivity"
android:screenOrientation="portrait"
android:persistent="true"/>
<activity
android:name=".alarm.AlarmCanceledActivity"
android:screenOrientation="portrait" />
<activity
android:name=".alarm.AlarmSuccesfulActivity"
android:screenOrientation="portrait" />
<activity android:name=".menubar.ChangeProfilActivity"></activity>
<activity android:name=".connectBracelet.AddBraceletActivity"
android:screenOrientation="portrait">
</activity>
<activity android:name=".menubar.ChangeProfilActivity">
</activity>
</application>
</manifest>
AddBraceletActivity.kt
package com.example.notfallapp.connectBracelet
import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.notfallapp.MainActivity
import com.example.notfallapp.R
import com.example.notfallapp.interfaces.ICreatingOnClickListener
class AddBraceletActivity : Activity(), ICreatingOnClickListener {
private lateinit var btnSos: Button
private lateinit var btnHome: ImageButton
private lateinit var btnContact: ImageButton
private lateinit var btnAlarms: ImageButton
private lateinit var btnMap: ImageButton
private lateinit var btnSettings: ImageButton
private lateinit var btnRetrySearching: Button
private lateinit var btnCancel: Button
private lateinit var tvConnectBracelet: TextView
private lateinit var lvDevices: ListView
private lateinit var builder: AlertDialog.Builder
private var bAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
private lateinit var mReceiver: BroadcastReceiver
private var context = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_bracelet)
configureButtons()
initComponents()
btnCancel.setOnClickListener() {
Log.d("ButtonCancel", "Cancel Button was clicked in AddBraceletActivity")
sureDialog()
val alert = builder.create()
alert.show()
}
btnRetrySearching.setOnClickListener() {
Log.d("ButtonSearch", "Search Button was clicked in AddBraceletActivity")
searchDevices()
}
searchDevices()
}
private fun configureButtons() {
// SOS Button
btnSos = findViewById(R.id.btn_sos)
// Button bar
btnHome = findViewById(R.id.btnHome)
btnAlarms = findViewById(R.id.btnAlarms)
btnContact = findViewById(R.id.btnContact)
btnMap = findViewById(R.id.btnMap)
btnSettings = findViewById(R.id.btnSettings)
createOnClickListener(this, btnSos, btnHome, btnAlarms, btnContact, btnMap, btnSettings)
}
private fun initComponents() {
btnRetrySearching = findViewById(R.id.btn_retry_searching)
btnCancel = findViewById(R.id.btn_cancel_searching_device)
tvConnectBracelet = findViewById(R.id.tvConnectBracelet)
lvDevices = findViewById(R.id.lvDevices)
builder = AlertDialog.Builder(this)
mReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
System.out.println("Hello 2")
val action = intent.action
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED == action) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND == action) {
//bluetooth device found
val device =
intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice
val toast = Toast.makeText(context, "Found device " + device.name, Toast.LENGTH_LONG)
toast.show()
}
}
}
}
private fun searchDevices() {
//TODO search for Bluetooth devices.
Log.d("SearchDevices", "SearchDevices was called in AddBraceletActivity")
if (bAdapter == null) {
tvConnectBracelet.setError(getResources().getString(R.string.deviceNotSupportBluetooth))
return;
}
if (!bAdapter.isEnabled) {
val eintent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivity(eintent)
}
val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300)
}
startActivity(discoverableIntent)
if (bAdapter.isDiscovering){
bAdapter.cancelDiscovery()
}
/*val pairedDevices = bAdapter.bondedDevices
if (pairedDevices.size > 0) {
// There are paired devices. Get the name and address of each paired device.
for (device in pairedDevices) {
System.out.println(device.address)
}
}*/
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.i("info", "No fine location permissions")
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
1)
}
bAdapter.startDiscovery()
val onFoundFilter = IntentFilter(BluetoothDevice.ACTION_FOUND)
onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
onFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
registerReceiver(mReceiver, onFoundFilter)
}
override fun onDestroy() {
bAdapter.cancelDiscovery()
unregisterReceiver(mReceiver);
super.onDestroy();
}
private fun sureDialog() {
builder.setTitle(getResources().getString(R.string.confirm))
builder.setMessage(getResources().getString(R.string.sureStopSearching))
builder.setPositiveButton(getResources().getString(R.string.Yes)) { dialog, which ->
var intent = Intent(this, MainActivity::class.java)
startActivity(intent)
dialog.dismiss()
}
builder.setNegativeButton(getResources().getString(R.string.No)) {dialog, which ->
dialog.dismiss()
}
}
}
These are my files where I have the permissions and where I scan for bluetooth devices.
Thank you very much for help!
Hello I solved my problem by reinstall my device to the base settings.
I have an app that, when is first installed a splash screen appears and then a intro with 3 fragments appears and explains how the app works. However once the user walked through that "intro" only the splash screen appears. How should I do that? I belive this has to do my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pfinal">
<!-- Permissoes para o acesso a camera -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Permissoes para o acesso ao GPS -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_fire_round"
android:label="AppFogos"
android:roundIcon="#mipmap/ic_fire_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Intro">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- The below is for the splash screen and we need no action bar and the default theme -->
<activity
android:name=".SplashScreen"
android:theme="#style/AppTheme.NoActionBar">
<!-- <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>-->
</activity>
<activity android:name=".AppFogos" />
<activity android:name=".HomePage">
<!-- <intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>-->
</activity>
</application>
Intro is the activity with the walktrough and SplashScreen is the activity with the splash screen.
Right now, only the Intro appears.
Here is the code for the "Intro":
val fragment1 = SliderFragment()
val fragment2 = SliderFragment()
val fragment3 = SliderFragment()
lateinit var adapter : myPagerAdapter
lateinit var activity: Activity
lateinit var preference : SharedPreferences
val pref_show_intro = "Intro"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
activity = this
preference = getSharedPreferences("~PFinal", Context.MODE_PRIVATE)
if(!preference.getBoolean(pref_show_intro,true)){
startActivity(Intent(activity,SplashScreen::class.java))
finish()
}
fragment1.setTitle("welcome")
fragment2.setTitle("fogos")
fragment3.setTitle("o que utilizamos")
adapter = myPagerAdapter(supportFragmentManager)
adapter.list.add(fragment1)
adapter.list.add(fragment2)
adapter.list.add(fragment3)
view_pager.adapter = adapter
next.setOnClickListener {
view_pager.currentItem++
}
skip.setOnClickListener { goToHomePage() }
view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
if(position == adapter.list.size-1)
{
//lastpage
next.text="DONE"
next.setOnClickListener {
goToHomePage()
}
}else{
next.text="NEXT"
next.setOnClickListener {
view_pager.currentItem++
}
}
when(view_pager.currentItem)
{
0->{
indicator1.setTextColor(Color.BLACK)
indicator2.setTextColor(Color.GRAY)
indicator3.setTextColor(Color.GRAY)
}
1->{
indicator1.setTextColor(Color.GRAY)
indicator2.setTextColor(Color.BLACK)
indicator3.setTextColor(Color.GRAY)
}
2->{
indicator1.setTextColor(Color.GRAY)
indicator2.setTextColor(Color.GRAY)
indicator3.setTextColor(Color.BLACK)
}
}
}
})
}
fun goToHomePage(){
startActivity(Intent(activity,HomePage::class.java))
finish()
val editor = preference.edit()
editor.putBoolean(pref_show_intro,false)
editor.apply()
}
class myPagerAdapter(manager : FragmentManager): FragmentPagerAdapter(manager){
val list : MutableList<Fragment> = ArrayList()
override fun getItem(position: Int): Fragment {
return list[position]
}
override fun getCount(): Int {
return list.size
}
}
I apologize for my English.
I have a problem with redirecting to a subpage of Google results, SMS to WebView Android applications.
Example: The page with the address https://siteadress.pl/category in the Google results opens the WebView application and shows the homepage (https://siteadress.pl/)
LOOK PICTURE
Example: A page with the exact product https://siteadress.pl/shop/productxyz in Google results also opens the WebView application and shows the homepage. Why?
The link (https://siteadress.pl/shop/productxyz) from the sms message also opens the WebView application and shows the main page.
I want to point to the exact page of the application in WebView, not the homepage. :(
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pl.APP">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="APP"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="asset_statements"
android:resource="#string/asset_statements" />
<activity
android:name=".SplashScreen"
android:launchMode="singleTop"
android:noHistory="true"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>
<activity android:name=".ContactActivity" />
<activity android:name=".CategoryActivity" />
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="siteadress.pl" />
</intent-filter>
</activity>
</application>
</manifest>
My MainActivity.xml
package pl.APP
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView.webViewClient = MyWebViewClient()
webView.loadUrl("https://siteadress.pl/")
webView.settings.javaScriptEnabled = true
}
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else {
super.onBackPressed()
}
}
inner class MyWebViewClient : WebViewClient()
{
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
{
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
#RequiresApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
{
val url=request?.url.toString()
if(URLUtil.isNetworkUrl(url))
{
return false
}
try
{
val shareIntent= Intent()
shareIntent.action=Intent.ACTION_VIEW
shareIntent.data= Uri.parse(url)
startActivity(shareIntent)
}
catch(e: ActivityNotFoundException)
{
Toast.makeText(this#MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
Log.e("AndroidRide",e.toString())
}
return true
}
}
}
Thanks for help :)
The solution is you need to handle app link first, get the correct link and then load that link into your WeView:
Uri data = getIntent().getData();
if (data != null) {
String url = data.toString();
webView.loadUrl(url);
} else {
webView.loadUrl("https://siteadress.pl/");
}
Done! This version in "Kotlin" work:
val url = intent.data.toString()
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url)
} else {
webView.loadUrl("https://siteadress.pl/")
}
Thanks for help :) ufff
problem in opening camera intent in android
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
var CAMERA_REQUEST_CODE = 0
lateinit var imageFilePath:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
try{
val imageFile=createImageFile()
val callCameraIntent= Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(callCameraIntent.resolveActivity(packageManager)!=null)
{
val authorities=packageName+".fileprovider"
val imageUri= FileProvider.getUriForFile(this,authorities,imageFile)
callCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)
startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE )
}
}
catch (e:Exception)
{
Toast.makeText(this,"Could not create" +
" file!",Toast.LENGTH_SHORT).show()
}
}
}
// MY ACTIVITYRESULT FUNCTION
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode)
{
CAMERA_REQUEST_CODE -> {
if(resultCode == Activity.RESULT_OK)
{
photoImageView.setImageBitmap(setScaledBitmap())
}
}
else -> {
Toast.makeText(this,"Unrecognized " +
"result code",Toast.LENGTH_SHORT).show()
}
}
}
// MY ACTIVITYRESULT FUNCTION
#Throws(IOException::class)
fun createImageFile(): File
{
val timestamp=SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(Date())
val imageFileName = "JPEG_"+timestamp + "_"
val storageDir=getExternalFilesDir(Environment.DIRECTORY_PICTURES)
if(!storageDir.exists())
{
storageDir.mkdirs()
}
val imageFile= createTempFile(imageFileName,".jpg",storageDir)
imageFilePath=imageFile.absolutePath
return imageFile
}
fun setScaledBitmap():Bitmap{
val imageViewWith =photoImageView.width
val imageViewHeight =photoImageView.height
val bmOptions=BitmapFactory.Options()
bmOptions.inJustDecodeBounds=true
BitmapFactory.decodeFile(imageFilePath,bmOptions)
val bitmapWidth=bmOptions.outWidth
val bitmapHeight=bmOptions.outHeight
val scaleFactor= Math.min(bitmapWidth/imageViewWith,bitmapHeight/imageViewHeight)
bmOptions.inSampleSize=scaleFactor
bmOptions.inJustDecodeBounds=false
return BitmapFactory.decodeFile(imageFilePath,bmOptions)
}
}
// MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hi.httpwww.hi">
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="$(applicationId).fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:resource="#xml/filepaths"
android:name="android.support.FILE_PROVIDER_PATHS"/>
</provider>
</application>
</manifest>
// filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="intent_images"
path="Pictures"/>
</paths>
I am facing problem in above code. When I start my activity it it says could not open file. Is that correct behaviour or I am doing anything wrong? without calling on destroy of my activity it is again coming inside on create.Need some help. Thank you.