Skip to content

Instantly share code, notes, and snippets.

@makorowy
Last active February 25, 2018 18:29
Show Gist options
  • Save makorowy/141aaf5db3c455ad7362a447247ac557 to your computer and use it in GitHub Desktop.
Save makorowy/141aaf5db3c455ad7362a447247ac557 to your computer and use it in GitHub Desktop.
TensorFlow - Hot or Not example. Taking a photo.
private const val REQUEST_PERMISSIONS = 1
private const val REQUEST_TAKE_PICTURE = 2
class MainActivity : AppCompatActivity() {
private var photoFilePath = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkPermissions()
}
private fun checkPermissions() {
if (arePermissionAlreadyGranted()) {
takePhoto()
} else {
requestPermissions()
}
}
private fun arePermissionAlreadyGranted() =
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
private fun requestPermissions() {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_PERMISSIONS)
}
private fun takePhoto() {
photoFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath + "/${System.currentTimeMillis()}.jpg"
val currentPhotoUri = UriHelper.getUriFromFilePath(this, photoFilePath)
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, currentPhotoUri)
takePictureIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
if (takePictureIntent.resolveActivity(packageManager) != null) {
startActivityForResult(takePictureIntent, REQUEST_TAKE_PICTURE)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == REQUEST_PERMISSIONS && arePermissionGranted(grantResults)) {
takePhoto()
} else {
requestPermissions()
}
}
private fun arePermissionGranted(grantResults: IntArray) =
grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val file = File(photoFilePath)
if (requestCode == REQUEST_TAKE_PICTURE && file.exists()) {
//classify photo
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment