ARouter使用
1. androidstudio3.0配置
javaCompileOptions {
annotationProcessorOptions {
arguments = [AROUTER_MODULE_NAME: project.getName()]
}
}
dependencies { implementation 'com.alibaba:arouter-api:1.4.0' annotationProcessor 'com.alibaba:arouter-compiler:1.2.1' }
2. 使用
2.1初始
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); ARouter.openLog(); ARouter.openDebug(); ARouter.init(this); } }
2.2 页面切换
/*为activity添加注解, path最少两级*/ @Route(path = "/activity/main2") public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } }
/*调用方式*/
ARouter.getInstance().build("/activity/main2").navigation();
2.3 URL跳转
/*统一*/
public class SchemeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scheme); ARouter.getInstance().build(getIntent().getData()).navigation(); finish(); } }
manifest配置SchemeActivity
<activity android:name=".SchemeActivity" >
<intent-filter>
<data android:host="nep.demo.com"
android:scheme="aroute"
/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
//被调用的Activity
@Route(path = "/activity/main3")
public class Main3Activity extends AppCompatActivity {
@Autowired
String name ;
@AUtowired
Items obj; //自定义数据
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2);
ARouter.getInstance().inject(this);
Log.i("TAG", "name:"+name);
Log.i("TAG", obj.toString());
}
}
//Items定义
public class Items {
private String name;
private int id;
public Items(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return name + " " + id;
}
}
//定义自定义对象转换类
@Route(path = "/service/json") //path 自由命名
public class JsonObject implements SerializationService {
Gson mGson;
private void check(){
if (mGson==null) {
mGson = new Gson();
}
}
@Override
public <T> T json2Object(String input, Class<T> clazz) {
check();
return mGson.fromJson(input, clazz);
}
@Override
public String object2Json(Object instance) {
check();
return mGson.toJson(instance);
}
@Override
public <T> T parseObject(String input, Type clazz) {
check();
return mGson.fromJson(input, clazz);
}
@Override
public void init(Context context) {
check();
}
}
调用方式:
Gson gson = new Gson();
String json = gson.toJson(new Items("heloo", 11111));
Uri uri = Uri.parse("aroute://nep.pax.com/activity/main3?name=hello&obj=" + json);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);