Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Android routing Framework ARouter

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge about how to use the Android routing framework ARouter. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Add dependency and initialization framework

1. Add dependencies

Add the following code to the module where you need to use ARouter:

1.1.The java version depends on android {defaultConfig {... JavaCompileOptions {annotationProcessorOptions {arguments = [moduleName: project.getName ()]} dependencies {api 'com.alibaba:arouter-api:1.5.1' annotationProcessor' com.alibaba:arouter-compiler:1.5.1'} 1.2, dependent plugins for kotlin version {... Id 'kotlin-kapt'} dependencies {... Implementation 'com.alibaba:arouter-api:1.5.1' kapt' com.alibaba:arouter-compiler:1.5.1'}

Digression: implementation and api keywords. In the Android studio3.0 version, the former compile keyword is discarded, while api is a substitute for compile. Api is no different from compile. But the latest official recommendation is to use implementation instead of the compile keyword, and implementation is said to make Android studio compile faster.

The difference between the implementation and api keywords is that the dependency package declared in implementation is limited to the current module internal use, and cannot be used by modules that rely on its module. When using api to declare dependency packages, modules that depend on that module can normally use the dependency packages within their modules.

Here, because I'm putting it into a public module to make app module dependent, I use the api keyword. If the project is not componentized, you can rely on it using the implementation keyword.

2. Initialize SDK// initialize ARouter framework private boolean isDebugARouter = true;//ARouter debug switch if (isDebugARouter) {/ / the following two lines must be written before init, otherwise these configurations will be invalid ARouter.openLog () in init; / / enable debug mode (if running in InstantRun mode, debug mode must be enabled! / / the online version needs to be closed, otherwise there is a security risk) ARouter.openDebug ();} / / it is officially recommended to initialize ARouter.init ((Application) mContext) in Application; 2. Simple use of ARouter

1. Interface jump

1.1.The Activity interface jumps.

Add comments to the destination Activity (jump statement, it is recommended to write the routing path as a constant, and create a routing table for unified management. )

@ Route (path = "/ app/login") public class LoginActivity extends AppCompatActivity {

Send Activity to implement the jump to

ARouter.getInstance (). Build ("/ app/login"). Navigation (). 1.2.get fragment instance / / target interface @ Route (path = "/ app/fragment") public class EmptyFragment extends BaseFragment {} / / launch interface Fragment fragment= (Fragment) ARouter.getInstance (). Build ("/ app/fragment"). Navigation (); FragmentManager manager = getSupportFragmentManager (); FragmentTransaction transaction = manager.beginTransaction (); transaction.add (R.id.fl_fragment_content, fragment); transaction.commit ()

If the students who have componentized the project like me will find that the jump is not successful at this time, but a pop-up error prompt.

This is because even after componentization, we use api as the dependent keyword, but we still need to configure the code in other module that uses ARouter. The general practice here is to put the arouter-api dependency in the module of the basic service, because since componentization is used, it is certain that all module needs to rely on the arouter-api library, while the arouter-compiler dependency needs to be placed in every module.

Java

Android {defaultConfig {... JavaCompileOptions {annotationProcessorOptions {arguments = [moduleName: project.getName ()]} dependencies {annotationProcessor 'com.alibaba:arouter-compiler:1.5.1'}

Kotlin

Plugins {... Id 'kotlin-kapt'} dependencies {... Kapt 'com.alibaba:arouter-compiler:1.5.1'}

Otherwise, the route cannot be matched, and an error will be reported when you use the withObject method to carry objects. Later, try again and find that the interface successfully jumps. With regard to the path parameter of the annotation @ Route, you should also pay attention to the specification, which must start with "/" and the path must be at least two levels, otherwise it will fail or report an error.

This means that the path must start with "/" and contain more than 2 "/" values.

2. Interface jump with basic parameters

The method is as follows, pass in the key-value pair

Bundle bundle = new Bundle (); bundle.putString ("bundleStringKey", "bundleStringValue"); ARouter.getInstance (). Build ("/ app/login") .withString ("stringKey", "stringValue") .withInt ("intKey", 100) .withBoolean ("booleanKey", true) .withBundle ("bundle", bundle) .withstring ()

The target interface is injected with @ Autowired annotations

@ Route (path = "/ app/login") public class LoginActivity extends AppCompatActivity {@ Autowired String stringKey; @ Autowired int intKey; @ Autowired boolean booleanKey; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_login); / / inject ARouter ARouter.getInstance () .inject (this) Log.e (TAG, stringKey + "..." + intKey + "..." + booleanKey); Log.e (TAG, bundle.getString ("bundleStringKey"));}}

Note: the property name of the injection should be exactly the same as the key value carried before, and the ARouter should be injected through ARouter.getInstance (). Inject (this) in the interface that needs to be injected, otherwise the injection will not succeed. It is recommended that you put the ARouter.getInstance (). Inject (this) operation in the onCreate method of BaseActivity. Since there is injection, there must be a release of resources, so the release of resources takes place in Application.

Override public void onTerminate () {super.onTerminate (); ARouter.getInstance () .destroy ();}

If ARouter.getInstance () .destroy () is called in the onDestroy method of BaseActivity for releasing resources; after entering the target Activity, and then pressing the back key to return to the original interface, APP will report an error and crash. Here is the crash log:

3. Interface jump of carrying objects

3.1. Interface jump with serialized objects

Objects that carry Serializable and Parcelable serialization

TestSerializableBean serializableBean = new TestSerializableBean (); serializableBean.setName ("serializable"); TestParcelableBean parcelableBean = new TestParcelableBean (); parcelableBean.setName ("parcelable"); ARouter.getInstance (). Build ("/ app/login"). WithParcelable ("parcelableBean", parcelableBean). WithSerializable ("serializableBean", serializableBean).

Target interface

@ AutowiredTestParcelableBean parcelableBean;@AutowiredTestSerializableBean serializableBean;@Overrideprotected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_login); Log.e (TAG, parcelableBean + ""); Log.e (TAG, serializableBean + ");}

We found that the object serialized by Serializable is null, and we look at the withSerializable method and find that it is loaded into Bundle

Public Postcard withSerializable (@ Nullable String key, @ Nullable Serializable value) {mBundle.putSerializable (key, value); return this;}

So change the method to get the value, and find that the print is successful.

TestSerializableBean serializableBean = (TestSerializableBean) getIntent () .getExtras () .getSerializable ("serializableBean"); Log.e (TAG, serializableBean + "")

3.2. Interface jump with unserialized objects

Objects that have not been serialized can also be passed through withObject objects in the same way.

NormalTest normalTest = new NormalTest (); normalTest.setName ("normal"); ARouter.getInstance (). Build ("/ app/login"). WithObject ("normalTest", normalTest).

But if we use this method directly, we will report an error. After analyzing the source code, we find that SerializationService is used in this method.

Public Postcard withObject (@ Nullable String key, @ Nullable Object value) {serializationService = ARouter.getInstance () .navigation (SerializationService.class); mBundle.putString (key, serializationService.object2Json (value)); return this;}

So we need to implement the service.

@ Route (path = "/ service/json") public class JsonServiceImpl implements SerializationService {private Gson gson; @ Override public T json2Object (String input, Class clazz) {return gson.fromJson (input, clazz);} @ Override public String object2Json (Object instance) {return gson.toJson (instance);} @ Override public T parseObject (String input, Type clazz) {return gson.fromJson (input, clazz) @ Override public void init (Context context) {gson = new Gson ();}}

We can define the required json parser in it and run it again to print the object successfully. Can serialized objects be passed using this method?

TestParcelableBean objParcelableBean = new TestParcelableBean (); objParcelableBean.setName ("objParcelable"); TestSerializableBean objSerializableBean = new TestSerializableBean (); objSerializableBean.setName ("objSerializable"); NormalTest normalTest = new NormalTest (); normalTest.setName ("normal"); ARouter.getInstance (). Build ("/ app/login") .withobject ("objParcelableBean", objParcelableBean) .withobject ("objSerializableBean", objSerializableBean) .withObject ("normalTest", normalTest) .objective (); / / Target interface @ Autowired (name = "objParcelableBean") TestParcelableBean objParcelableBean @ Autowired (name = "objSerializableBean") TestSerializableBean objSerializableBean;@Autowired (name = "normalTest") NormalTest normalTest;Log.e (TAG, objParcelableBean + ""); Log.e (TAG, objSerializableBean + ""); Log.e (TAG, normalTest + "")

We found that the object serialized with Parcelable is empty, analyze the compiled file of build

@ Override public void inject (Object target) {serializationService = ARouter.getInstance () .navigation (SerializationService.class); LoginActivity substitute = (LoginActivity) target; substitute.objParcelableBean = substitute.getIntent () .getParcelableExtra ("objParcelableBean"); if (null! = serializationService) {substitute.objSerializableBean = serializationService.parseObject (substitute.getIntent () .getStringExtra ("objSerializableBean"), new com.alibaba.android.arouter.facade.model.TypeWrapper () {} .getType ()) } else {Log.e ("ARouter::", "You want automatic inject the field 'objSerializableBean' in class' LoginActivity', then you should implement 'SerializationService' to support object auto inject!");} if (null! = serializationService) {substitute.normalTest = serializationService.parseObject (substitute.getIntent (). GetStringExtra ("normalTest"), new com.alibaba.android.arouter.facade.model.TypeWrapper () {} .getType ()) } else {Log.e ("ARouter::", "You want automatic inject the field 'normalTest' in class' LoginActivity', then you should implement 'SerializationService' to support object auto inject!");}}

We can see that only the objects serialized through Parcelable do not parse using SerializationService, but are fetched directly from Bundle, but we do not set the value through the withParcelable method, so the data obtained is null.

Summary: therefore, to facilitate our operation, objects that are not serialized and serialized using Serializable are passed using the withObject method, and objects serialized using Parcelable are passed using the withParcelable method.

3.3. Interface jump with sets and arrays

The interface jumps of collections and arrays are passed uniformly using the withObject method, and can support various serialization of members.

List listNormal = new ArrayList (); listNormal.add (new NormalTest ()); listNormal.add (new NormalTest ()); List listSerializable = new ArrayList (); listSerializable.add (new TestSerializableBean ()); listSerializable.add (new TestSerializableBean ()); List listParcelable = new ArrayList (); listParcelable.add (new TestParcelableBean ()); listParcelable.add (new TestParcelableBean ()); Map map = new HashMap (); map.put ("1", new NormalTest ()); map.put ("2", new NormalTest ()) ARouter.getInstance () .build ("/ app/login") .withObject ("listNormal", listNormal) .withObject ("listSerializable", listSerializable) .withObject ("listParcelable", listParcelable) .withObject ("map", map) .withobject (); / / Target interface @ Autowired List listNormal; @ Autowired List listSerializable; @ Autowired List listParcelable; @ Autowired Map map; Log.e (TAG, listNormal + "") Log.e (TAG, listSerializable + ""); Log.e (TAG, listParcelable + ""); Log.e (TAG, map + "")

4. Interface jump callback / / launch interface ARouter.getInstance (). Build ("/ app/login") .launch (MainActivity.this, REQUEST_CODE); @ Override protected void onActivityResult (int requestCode, int resultCode, @ Nullable Intent data) {super.onActivityResult (requestCode, resultCode, data); if (requestCode = = REQUEST_CODE&& resultCode = = RESULT_CODE) {LogUtils.e (data.getStringExtra ("data")) }} / / Target interface Intent intent = new Intent (); intent.putExtra ("data", "resultData"); setResult (RESULT_CODE, intent); finish (); these are all the contents of the article "how to use Android routing Framework ARouter". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report