Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

activity 3 dz Alekseev Igor #147

Open
wants to merge 1 commit into
base: homework/activity_03
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,8 @@ dependencies {
implementation 'androidx.activity:activity-ktx:1.9.0'
implementation 'androidx.fragment:fragment-ktx:1.7.1'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'androidx.compose.runtime:runtime-android:1.7.5'
implementation 'androidx.compose.ui:ui-android:1.7.5'
implementation 'androidx.compose.material3:material3-android:1.3.1'
implementation 'androidx.activity:activity:1.9.3'
}
21 changes: 20 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-feature
android:name="android.hardware.camera"
android:required="true" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
Expand All @@ -12,7 +20,9 @@
android:supportsRtl="true"
android:theme="@style/Theme.Activities"
tools:targetApi="31">

<activity
android:name=".FillFormActivity"
android:exported="false" />
<activity
android:name=".EditProfileActivity"
android:exported="true">
Expand All @@ -22,6 +32,15 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="otus.gpb.homework.activities"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>

</manifest>
151 changes: 150 additions & 1 deletion app/src/main/java/otus/gpb/homework/activities/EditProfileActivity.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
package otus.gpb.homework.activities

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.FileProvider
import androidx.core.graphics.drawable.toBitmap
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

const val KEY_FIRST_NAME = "FIRST_NAME"
const val KEY_SECOND_NAME = "SECOND_NAME"
const val KEY_AGE = "AGE"

class EditProfileActivity : AppCompatActivity() {

private enum class AlertsDlg {DLG_PHOTO, DLG_SECOND_CAMERA_PERMISSION_REQ, DLG_OPEN_SETTINGS}
private enum class Menu(val value: Int) { TAKE_PHOTO(0), SELECT_PHOTO(1)}
private lateinit var imageView: ImageView

override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -28,6 +55,98 @@ class EditProfileActivity : AppCompatActivity() {
}
}
}

findViewById<ImageView>(R.id.imageview_photo).setOnClickListener {
AlertDialog.Builder(this).apply {
setTitle("Фото")
setIcon(android.R.drawable.ic_dialog_info)
setItems(arrayOf("Сделать фото", "Выбрать фото"), AlertsDlgClickListener(AlertsDlg.DLG_PHOTO))
setNegativeButton("Отмена", null)
show()
}
}

findViewById<Button>(R.id.button4).setOnClickListener{
fillFormActivityLauncher.launch(Intent(this, FillFormActivity::class.java))
}
}

//Первая попытка запросить разрешение на использование камеры
private val permissionCameraFirst = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
granted ->
if (granted) findViewById<ImageView>(R.id.imageview_photo).setImageResource(R.drawable.cat)
}

//Вторая попытка запросить разрешение на использование камеры
private val permissionCameraSecond = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
granted ->
if (!granted){
AlertDialog.Builder(this@EditProfileActivity).apply {
setIcon(android.R.drawable.ic_dialog_info)
setMessage("В настройках необходимо дать разрешение на использование камеры.")
setPositiveButton("Открыть настройки", AlertsDlgClickListener(AlertsDlg.DLG_OPEN_SETTINGS))
show()
}
}
}

private val pickPhoto = registerForActivityResult(ActivityResultContracts.GetContent()) {
uri -> if( uri != null) populateImage(uri)
}

private val fillFormActivityLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) {
result ->
val data = result.data
val code = result.resultCode

if( code == RESULT_OK && data != null){
val str = data.getStringExtra(KEY_FIRST_NAME)
findViewById<TextView>(R.id.textview_name).text = data.getStringExtra(KEY_FIRST_NAME)
findViewById<TextView>(R.id.textview_surname).text = data.getStringExtra(KEY_SECOND_NAME)
findViewById<TextView>(R.id.textview_age).text = data.getStringExtra(KEY_AGE)
}
}

private inner class AlertsDlgClickListener(val dialod: AlertsDlg) : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
when(dialod) {
AlertsDlg.DLG_PHOTO -> {
when (which) {
Menu.TAKE_PHOTO.value -> {
when
{
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
findViewById<ImageView>(R.id.imageview_photo).setImageResource(R.drawable.cat)
}

shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) -> {
AlertDialog.Builder(this@EditProfileActivity).apply {
setTitle("Ранее Вы запретили к камере доступ")
setMessage("Чтобы сделать фото необходимо разрешение на использование камеры.")
setIcon(android.R.drawable.ic_dialog_info)
setPositiveButton("Дать доступ", AlertsDlgClickListener(AlertsDlg.DLG_SECOND_CAMERA_PERMISSION_REQ))
setNegativeButton("Отмена", null)
show()
}
}

else -> permissionCameraFirst.launch(Manifest.permission.CAMERA)
}
}

Menu.SELECT_PHOTO.value -> pickPhoto.launch("image/*")
}
}

AlertsDlg.DLG_SECOND_CAMERA_PERMISSION_REQ ->
permissionCameraSecond.launch(Manifest.permission.CAMERA)

AlertsDlg.DLG_OPEN_SETTINGS ->
startActivity( Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.fromParts("package", packageName, null)))
}

}
}

/**
Expand All @@ -39,6 +158,36 @@ class EditProfileActivity : AppCompatActivity() {
}

private fun openSenderApp() {
TODO("В качестве реализации метода отправьте неявный Intent чтобы поделиться профилем. В качестве extras передайте заполненные строки и картинку")
var text = "Имя:" + findViewById<TextView>(R.id.textview_name).text.toString() + "\n"
text += "Фамилия:" + findViewById<TextView>(R.id.textview_surname).text.toString() + "\n"
text += "Возраст:" + findViewById<TextView>(R.id.textview_age).text.toString()

val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
putExtra(Intent.EXTRA_STREAM, getBitmapUriFromBitmap(this@EditProfileActivity, imageView.drawable.toBitmap()))
setPackage("org.telegram.messenger");
type = "*/*"
}

val shareIntent = Intent.createChooser(sendIntent, "Отправить через...")
startActivity(shareIntent)
}

private fun getBitmapUriFromBitmap(context: Context, bitmap: Bitmap): Uri? {
var bmpUri: Uri? = null
try {
val file = File(
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"share_image_${System.currentTimeMillis()}.png"
)
val out = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)
out.close()
bmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file)
} catch (e: IOException) {
e.printStackTrace()
}
return bmpUri
}
}
32 changes: 32 additions & 0 deletions app/src/main/java/otus/gpb/homework/activities/FillFormActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package otus.gpb.homework.activities

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FillFormActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_fill_form)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.textViewFirstName)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

findViewById<Button>(R.id.buttonApplay).setOnClickListener{
setResult(RESULT_OK, Intent().apply{
putExtra(KEY_FIRST_NAME, findViewById<EditText>(R.id.editTextFirstName).text.toString())
putExtra(KEY_SECOND_NAME, findViewById<EditText>(R.id.editTextSecondName).text.toString())
putExtra(KEY_AGE, findViewById<EditText>(R.id.editTextAge).text.toString())
})
finish()
}
}
}
62 changes: 62 additions & 0 deletions app/src/main/res/layout/activity_fill_form.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/textViewFirstName"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FillFormActivity">

<EditText
android:id="@+id/editTextFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="232dp"
android:layout_marginEnd="32dp"
android:ems="10"
android:inputType="text"
android:text="First Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editTextSecondName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:ems="10"
android:inputType="text"
android:text="Second Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextFirstName" />

<EditText
android:id="@+id/editTextAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:ems="10"
android:inputType="text"
android:text="Age"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextSecondName" />

<Button
android:id="@+id/buttonApplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:text="Применить"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextAge" />
</androidx.constraintlayout.widget.ConstraintLayout>
6 changes: 6 additions & 0 deletions app/src/main/res/xml/file_paths.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="external_files"
path="Pictures" />
</paths>