Original address :Jetpack Architecture component learning (3)——Activity Results API Use - Stars-One My groceries nest

Technology keeps pace with the times , Page Jump value transfer has been using startActivityForResult Method , Now there is a new API Realization way , Learn and summarize

startActivityForResult review

MainActivity Code :

Main2Activity Code :

effect :

The above code should be the basic code , I won't go into details here

Mainly about some shortcomings

All logic is in onActivityResult() The method is used to judge , according to requestCode and resultCode Judge

If it's OK to say , But if there are more , You will see onActivityResult() In a pile if Logic , It is very tedious to read , And maintenance is difficult

Google officials also took this into account , So we launched a new version Activity Results API To replace the way described above , Here's how to use

Easy to use

1. Introduce dependencies

First , We need to introduce dependencies :

implementation 'androidx.appcompat:appcompat:1.3.1'

PS: Please use 1.3.1 Above version , The lower version does not have this enumeration class ActivityResultContracts

Let's start with the above example , Use Activity Results API

Main2Acitivity The code doesn't move , We just need to adjust MainActivity The code in the file , As shown below :

2. Create a contract

val contract = ActivityResultContracts.StartActivityForResult()

contract The object class name of the variable is ActivityResultContract

ActivityResultContracts Equivalent to an enumeration class , It's officially sealed by Google , There are some commonly used ActivityResultContract Class object for us to use

Like taking pictures , Apply for permission , You can see from the code prompt , As shown in the figure below :

Here we choose StartActivityForResult(), The literal meaning should be easy to understand , It is applied in the scenario that the page jumps and returns data

PS: According to our choice ActivityResultContracts, Will affect the 4 The parameter type in the step

The corresponding selection instructions are supplemented below :

  • StartActivityForResult: General purpose Contract, No conversion ,Intent As input ,ActivityResult As the output , This is also the most commonly used protocol .
  • CreateDocument: Prompt the user to select a document , Return to one (file:/http:/content:) At the beginning Uri.
  • GetContent: Prompt to select a content , Return a pass through ContentResolver#openInputStream(Uri) Access to native data Uri Address (content:// form ) . By default , It increases the Intent#CATEGORY_OPENABLE, Return the content that can represent the stream .
  • GetMultipleContents: Get multiple items
  • OpenDocument: Prompt the user to select a file of the specified type ( Input parameter is mimeType), Returns the file selected by the user Uri
  • OpenDocumentTree: Prompt the user to select a directory , And return the user selected as a Uri return , The application can fully manage the documents returned to the directory .
  • OpenMultipleDocuments: Prompt the user to select a document ( Multiple can be selected ), Return their... Respectively Uri, With List In the form of .
  • PickContact: From address book APP Get contacts
  • RequestMultiplePermissions: Used to request a set of permissions
  • RequestPermission: Used to request a single permission
  • TakePicturePreview: call MediaStore.ACTION_IMAGE_CAPTURE Taking pictures , The return value is Bitmap picture
  • TakePicture: call MediaStore.ACTION_IMAGE_CAPTURE Taking pictures , And save the picture to the given Uri Address , return true Indicates that the save was successful .
  • TakeVideo: call MediaStore.ACTION_VIDEO_CAPTURE Take a video , Save to given Uri Address , Return a thumbnail .

See the documentation when specific parameters and descriptions can be used ~

actually , If the above list does not meet our needs , Then we can also customize the contract operation , The following part of the article will be supplemented , I won't extend it here

3. Build a contract ( register Contact)

// register ActivityResultContract
val myLauncher = registerForActivityResult(contract){
if (it.resultCode==2) {
val data = it.data
if (data != null) {
val resultData = data.getStringExtra("mydata")
Toast.makeText(this, resultData, Toast.LENGTH_SHORT).show()
}
}
}

Use Activity Class registerForActivityResult() Method , Register the deed , In fact, it is equivalent to registering a listener , After from Main2Activity Page back MainActivity page , Will call back the methods in this

Be careful : Here's a variable myLauncher, The third step is to use

4. Initiate page Jump

val intent = Intent(this, Main2Activity::class.java)
myLauncher.launch(intent)

call myLauncher Object's launch() Method , take intent Object transfer can realize the operation of page Jump

PS: This is still in the button click event , Easy to read omits

After from Main2Activity After the page returns , The operation in step 2 will be recalled , The effect is consistent with the above dynamic illustration , There is no need to re post a picture here

Customize ActivityResultContract

ActivityResultContract There are actually two generic types , Complete should be like this ActivityResultContract<I,O>

  • I by input It means , Meaning for Input parameter type
  • O by output It means , Meaning for Output parameter type

ActivityResultContract<I,O> It's an abstract class , We want to implement customization , Then inherit it directly

class MyContract: ActivityResultContract<String, String>() {

    override fun createIntent(context: Context, input: String?): Intent {
// here input The type of , Just as mentioned above I
} override fun parseResult(resultCode: Int, intent: Intent?): String {
// Here, the result type returned by the method , Just as mentioned above O } }

Inheritance discovery , We need to implement two methods ,createIntent() and parseResult()

A glance at the past is actually easy to understand ,createIntent() To create a intent object , call launch() Method time ( The number used above 4 Step by step ), It will be based on this intent Jump to the page

and parseResult() Method , It is the step of establishing the contract , The data type of callback inside

Let's take the example above , It is found that we have to make a statement Intent Object delivery , And when you send it back, you have to pass intent Object to get data , A little fussy , Some of the code can be encapsulated into generic

According to this idea , We can achieve one Customize ActivityResultContract, Pass the page parameters to get Main2Activity Returned data , The code is as follows :

class MyContract: ActivityResultContract<KClass<out Activity>, String>() {

    override fun parseResult(resultCode: Int, intent: Intent?): String? {
if (resultCode == 2 && intent!=null) {
return intent.getStringExtra("mydata")
}
return null
} override fun createIntent(context: Context, input: KClass<out Activity>?): Intent {
val intent = Intent(context,input?.java)
return intent
} }

Use :

//1. Create a contract 
val contract = MyContract() //2. register ActivityResultContract
val myLauncher = registerForActivityResult(contract){
Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
} btnGo.setOnClickListener {
//2. Initiate page Jump
myLauncher.launch(Main2Activity::class)
}

Of course , You can also optimize , If we let MyContract Multiple constructors , This is the value key This can also be used to define

class MyContract(val key: String) : ActivityResultContract<KClass<out Activity>, String>() {

    override fun parseResult(resultCode: Int, intent: Intent?): String? {
if (resultCode == 2 && intent != null) {
return intent.getStringExtra(key)
}
return null
} override fun createIntent(context: Context, input: KClass<out Activity>?): Intent {
val intent = Intent(context, input?.java)
return intent
} }

Use :

// Create a contract and transfer parameters 
val contract = MyContract("mydata")

Reference resources

Jetpack Architecture component learning (3)——Activity Results API Use more related articles

  1. Jetpack Architecture component learning (1)——LifeCycle Use

    Original address :Jetpack Architecture component learning (1)--LifeCycle Use | Stars-One My groceries nest Look at the other articles in this series , You can access this link Jetpack Architecture learning | Stars-One My groceries nest lately ...

  2. Jetpack Architecture component learning (2)——ViewModel and Livedata Use

    Look at the other articles in this series , You can access this link Jetpack Architecture learning | Stars-One My groceries nest Original address :Jetpack Architecture component learning (2)--ViewModel and Livedata Use | Stars-One ...

  3. Jetpack Architecture components Room database ORM MD

    Markdown Version notes my GitHub home page My blog My WeChat My mailbox MyAndroidBlogs baiqiantao baiqiantao bqt20094 [email protected] ...

  4. Jetpack Architecture components LiveData ViewModel MD

    Markdown Version notes my GitHub home page My blog My WeChat My mailbox MyAndroidBlogs baiqiantao baiqiantao bqt20094 [email protected] ...

  5. Jetpack Architecture components Lifecycle Life cycle MD

    Markdown Version notes my GitHub home page My blog My WeChat My mailbox MyAndroidBlogs baiqiantao baiqiantao bqt20094 [email protected] ...

  6. Android framework :Android Jetpack Learning and analysis of architecture components

    Reference resources :https://mp.weixin.qq.com/s/n-AzV7Ke8wxVhmC6ruUIUA Reference resources :https://jekton.github.io/2018/06/30/android- ...

  7. Android Jetpack Best practices for architectural components “ The net suppresses the cloud ”APP

    background In recent years ,Android Related new technologies emerge in endlessly . Often this technology is not finished , The next new technology is coming out again . Many people have black question marks on their faces ? Many developers even began to wail :" Please stop creating new technology , We can't learn !& ...

  8. Android One of the four components of learning Activity 6、 ... and

    This section studies Activity State preservation and recovery of . Let's start with an example : The layout file is mainly used to implement, for example, the following . You write it yourself Activity Logic code : public class FiveActivity extends A ...

  9. Jetpack Architecture components Paging Paging load MD

    Markdown Version notes my GitHub home page My blog My WeChat My mailbox MyAndroidBlogs baiqiantao baiqiantao bqt20094 [email protected] ...

  10. Jetpack Architecture components ( Two )Lifecycle Use

    1. The following dependencies can be added directly to meet the daily work , If which library is missing , Just add it separately implementation "android.arch.lifecycle:extensions:1.1.1& ...

Random recommendation

  1. BeanFactory and ApplicationContext(Bean Factory and application context )

    Bean factory (BeanFactory Interface ), Provides basic dependency injection support . Application context (ApplicationContext Interface ), Based on the Bean On a factory basis , Provides system architecture services . Application ...

  2. BC.5200.Trees(dp)

    Trees  Accepts: 156  Submissions: 533  Time Limit: 2000/1000 MS (Java/Others)  Memory Limit: 65536/6 ...

  3. C# Parallel library (TaskParallelLibrary) Summary of usage

    Free today , To sum up .NET 4.5 Parallel library (TaskParallelLibrary) usage . Maybe C and C++ Our programmers are just beginning to write C# Also used to new Thread To create a new thread , But creating a new thread requires memory and CPU Up and down ...

  4. hdoj4906 Our happy ending(2014 Multi-University Training Contest 4)

    For a fixed length (size = n) Sequence of numbers a, If it exists “ Location dependent ” Subset ( Empty set ) Make the sum of all the elements of the subset k, Then put the number in sequence a Count . The sequence of numbers a Any element of a[i] stay [0, l] Internal free value . Data conditions 0≤n, ...

  5. IE The browser opens to JavaScript Script support

    stay IE Browser's " Tools " From the menu "internet Options ", Select... In the pop-up command dialog box " Security " tab . Under this tab " The security level of the area & ...

  6. ( One )jdk8 Traversal of learning experience

    One . Traverse -- The best and stream Continuous use Use jdk8 Provided forEach When traversing , Multi thread operation is adopted , In theory, it will be faster than the original method . But notice , The system needs to be loaded at startup lambda The content of the framework . So if you pass ...

  7. Android Studio Debug the phone or install APK when install failed test only

    1. Check \app\src\main\AndroidMainfest.xml If there testOnly The attribute is true, If any, remove or change to false 2. Check Android Studio and gradle The version is ...

  8. UVA10410-Tree Reconstruction(BFS Preface and DFS The nature of order )

    Problem UVA10410-Tree Reconstruction Accept:708  Submit:4330 Time Limit: 3000 mSec Problem Descripti ...

  9. Kafka-Record( The message format )

    notes : This article relies on kafka-0.10.0.1-src kafka Message formats have evolved through multiple versions , This article only says 0.10.0.1 Version of the message format . The message format is shown in the figure 1 Shown : chart 1 CRC: Used to verify the message content . Occupy 4 Bytes ...

  10. 『TensorFlow Internals』 note _ Source structure

    zero . Data collection Know about columns :Bob Learn to walk Know and ask questions : How to study efficiently TensorFlow Code ?. Big brother Liu Guangcong (Github, Simple books ) Open source book :TensorFlow Internals, Strongly recommend ( This blog reference book ...