Getting Started with Arouter

    Aouter is an Android routing framework developed by the Ali team. This article aims to explain the Demo of the official website of Arouter, not its own Demo, because I think the official Demo is enough to meet the business needs of development, so I don't need to write another one by myself. , this article is some supplement to the documentation.

official address

git clone https://github.com/alibaba/ARouter.git God transfer download source code

Let's chat about the jump business functions that may be used in our project:

1. Activity jump and pass parameters (parameters include basic types and reference types)

2. Fragment jump, and pass parameters (parameters include basic types and reference types)

3. I want to do some judgment and control when jumping, or even intercept some interfaces and not give access to users without permission.

4. I want to decouple and not rely on a reference to an Activity

        The above four points basically meet our needs for jumping, but we cannot intercept the jumping of the interface natively. Points 1 and 2 can be achieved, but the repetitive work is very large, and when the jump is displayed, it depends on the Activity after the jump. .class , which makes us very passive when developing in parallel. If we use implicit jump, it will crash when Activity does not exist. Therefore, based on the above considerations, I have to introduce a routing framework to conduct research on Aouter After reading and reading the key source code, I decided to use this framework for development.

Provide an overview address of Liu Zhilong's explanation of the architecture and principles of Arouter. If you are interested, you can take a look:

Click to open the link  

Integrate Aouter

Aouter Api includes three types:

api :com.alibaba:arouter-api:x.x.x

Annotator: com.alibaba:arouter-compiler:xxx

        Auto-register plugin: com.alibaba:arouter-register:xxx

    (With the latest version as the column) Add in the app's build.gradle:

    

android {
    defaultConfig {
	...
	javaCompileOptions {
	    annotationProcessorOptions {
		arguments = [ moduleName : project.getName() ]
	    }
	}
    }
}
dependencies {
    // Replace with the latest version, note that the api
    // To match the compiler, use the latest version to ensure compatibility
    compile 'com.alibaba:arouter-api:1.3.1'
    annotationProcessor 'com.alibaba:arouter-compiler:1.1.4'
}

If AndroidStudio 3.0 gradle plugin 3.0 above compile use api to replace

If the version of the gradle plugin is less than 2.2, annotationProcessor needs to be replaced with the apt plugin

If it is a Kotlin project, please use the k-apt plugin to replace 

kotilin configuration column:

In the build.gradle of the project layer, add the plugin:

buildscript {
    ext.kotlin_version = '1.1.3-2'
    dependencies {
      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

The build.gradle of the app layer:

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
dependencies {
    kapt 'com.alibaba:arouter-compiler:1.0.3'
}

Note: If it is a componentized project, you need to pay attention to the configuration of javaCompileOptions and annotationProcessor 'com.alibaba:arouter-compiler:1.1.4' for each component, and the api can be placed in the basic library.

Configure the automatic registration plugin, in the build.gradle of the project layer:

  dependencies {
        classpath 'com.alibaba:arouter-register:1.0.2'
    }

The version api 1.3.1 corresponds to 1.0.2, it is wrong and invalid.


basic concepts

    annotation:

    1. @Route routing annotation. Defines a string where a target can be found, and is used for the path of Activity, Fragment, and Service.

    path: path string such as "test/activity1"

    Note: the new version of path must be set to a "XXX/XXX" slash type, because the string before a slash acts as a group

    group: group, deprecated in the new version

    name: The name of the definition path, the default is "undefined". to add comments

    priority: The priority defaults to -1.

    extras : Extra data, Interget type, which can be used to control the business logic of the target page. For example, 1 or 0 indicates whether a page is displayed or not. When the current 2 is banned, it can control 32 business switches. Generally not used.

    2. @Interceptor defines an interceptor. Adding this annotation can define an interceptor for global Activity jumps.

    priority: priority

    name: Default Default

    3. @Autowired injection parameters, used to receive transmission parameters or inject Service

    name: parameter name, default ""

    required: is it required, if true, the app will crash if the data is null

    desc: describing the parameter is equivalent to a comment

initialization

    

if (isDebug()) { // These two lines must be written before init, otherwise these configurations will be invalid during init
    ARouter.openLog(); // print log
    ARouter.openDebug(); // Turn on debug mode (if running in InstantRun mode, debug mode must be turned on! The online version needs to be turned off, otherwise there is a security risk)
}
ARouter.init(mApplication); // As early as possible, it is recommended to initialize in Application

Activity jump

    Simple Activity jump:

    Use Router to define routes

@Route(path = "/test/activity1")
public class Test1Activity extends AppCompatActivity {

    jump

ARouter
.getInstance()
.build("/test/activity1").navigation();
   

    Activity with basic parameters

    jump

ARouter.getInstance()
          .build("/test/activity2")
          .withString("key1", "value1")
          .navigation();

    withXX (key, value) transmits the basic type and can receive this data through key

     Use withObject (key, value) to transmit custom objects, use custom objects to implement the SerializationService interface, and specify that the route is set to @Route(path = "/service/json") . For example, serialize using FastJSON:

@Route(path = "/service/json")
public class JsonServiceImpl implements SerializationService {
    @Override
    public void init(Context context) {

    }

    @Override
    public <T> T json2Object(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

    @Override
    public String object2Json(Object instance) {
        return JSON.toJSONString(instance);
    }
}

    Parcelable and Serializable object transfers are directly supported.

    

    There are two ways to receive data

    One is the receiving method used natively

String value = getIntent().getXXXExtra("key");

    The other is to use annotation to get it, first add ARouter.getInstance().inject(this);

@Autowired(name="key")
String key;

    Match by name, by default by type match.

   Activity jump that needs to be returned

    

ARouter.getInstance()
       .build("/test/activity2")
       .navigation(this, 666);
setResult(666);
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 666:
                Log.e("activityResult", String.valueOf(resultCode));
                break;
            default:
                break;
        }
    }

 Activity for custom protocol jump

    Define the protocol:

 
 
<activity android:name=".SchemeFilterActivity">
            <!-- Shame -->
            <intent-filter>
                <data
                    android:host="m.aliyun.com"
                    android:scheme="arouter"/>

                <action android:name="android.intent.action.VIEW"/>

                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
      
        </activity>

The scheme defines the protocol header, which can be customized by yourself. m.aliun.com is the host

 When we jump, we need a middleman to schedule, such as: SchemeFilterActivity is used to schedule the protocol.

public class SchemeFilterActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);

// Process external Uri directly through ARouter
        Uri uri = getIntent (). GetData ();
        ARouter.getInstance().build(uri).navigation(this, new NavCallback() {
            @Override
            public void onArrival(Postcard postcard) {
                finish();
            }
        });
    }
}

When we want to jump, we can do this, for example, we need to jump to test/activity2

Uri testUriMix = Uri.parse("arouter://m.aliyun.com/test/activity2");
                ARouter.getInstance().build(testUriMix)
                        .withString("key1", "value1")
                        .navigation();

The above SchemeFilterActivity is just an intermediate schedule, not our target activity. Our target activity is test/activity2. Uri needs to be spliced ​​like this: protocol string + target jump path.

When SchemeFilterActivity receives the uri and then jumps again, getIntent().getData()=="test/activity2" taken out from SchemeFilterActivity.

We can also jump directly to the activity in the application on the webpage, and add Links to the intent-filter in the SchemeFilterActivity manifest file

<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:host="m.aliyun.com"
                    android:scheme="http"/>
                <data
                    android:host="m.aliyun.com"
                    android:scheme="https"/>
            </intent-filter>

Use tags <a></a> in html

<a href="arouter://m.aliyun.com/test/activity3?name=alex&age=18&boy=true&high=180">arouter://m.aliyun.com/test/activity3?name=alex&age=18&boy=true&high=180</a>
Behind? Then pass parameters. Equivalent to a get request.

Jump listener callback NavCallback

    

ARouter.getInstance().build("/xxx/xxx").navigation(this, new NavCallback() {
                    @Override
                    public void onFound(Postcard postcard) {
                        Log.d("ARouter", "Found");
                    }

                    @Override
                    public void onLost(Postcard postcard) {
                        Log.d("ARouter", "Can't find it");
                    }

                    @Override
                    public void onArrival(Postcard postcard) {
                        Log.d("ARouter", "Jump finished");
                    }

                    @Override
                    public void onInterrupt(Postcard postcard) {
                        Log.d("ARouter", "Intercepted");
                    }
                });

Use NavCallback to monitor whether the jump is intercepted, or whether the jump is completed. For example, we can perform some operations to save data after the jump, and when no Activity is found, it will prompt that the module is not open and other functions.

transition animation

The jump animation is also very simple to implement in Arouter. You only need to define the animation of entry and exit and call it as follows:

ARouter.getInstance()
    .build("/test/activity2")
    .withTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
    .navigation(this);
Many times people will ask why the setting is invalid. This may not be a problem with Arouter, but because your style sets android:windowIsTranslucent to true in order to prevent a black screen from appearing.

Transition animations for shared elements

             if (Build.VERSION.SDK_INT >= 16) {
                    ActivityOptionsCompat compat = ActivityOptionsCompat.
                            makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
                    ARouter.getInstance()
                            .build("/test/activity2")
                            .withOptionsCompat(compat)
                            .navigation();
                } else {
                    ARouter.getInstance()
                            .build("/test/activity2")
                            .navigation();
                }
Because shared elements are only supported when the API is greater than 16, we jump directly when less than 16.

Get Fragment

Add route:

@Route(path = "/test/fragment")
public class BlankFragment extends Fragment

jump with parameters

To be continued. . .



    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325539307&siteId=291194637