Skip to content

Commit 6c78b74

Browse files
authored
Merge pull request #18 from wyjsonGo/develop
publish v2.1.0 1.增加路由页面Event功能,参数5-10 2.添加对registerForActivityResult()方法的支持 3.修改go()方法组装card基础参数的顺序 4.修复生成文档没包含当前项目bug 5.优化生成文档过滤空值
2 parents c9d0f90 + ebe1c9f commit 6c78b74

File tree

27 files changed

+650
-78
lines changed

27 files changed

+650
-78
lines changed

GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,14 @@
1212
import android.os.Looper;
1313
import android.widget.Toast;
1414

15+
import androidx.activity.result.ActivityResultLauncher;
1516
import androidx.annotation.NonNull;
1617
import androidx.annotation.Nullable;
1718
import androidx.core.app.ActivityCompat;
19+
import androidx.core.app.ActivityOptionsCompat;
1820
import androidx.fragment.app.Fragment;
21+
import androidx.fragment.app.FragmentActivity;
22+
import androidx.lifecycle.Observer;
1923

2024
import com.wyjson.router.callback.GoCallback;
2125
import com.wyjson.router.callback.InterceptorCallback;
@@ -42,9 +46,6 @@
4246

4347
public final class GoRouter {
4448

45-
public static final String ROUTER_CURRENT_PATH = "go_router_current_path";
46-
public static final String ROUTER_RAW_URI = "go_router_raw_uri";
47-
4849
private final Handler mHandler = new Handler(Looper.getMainLooper());
4950
private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance();
5051
public static ILogger logger = new DefaultLogger();
@@ -278,23 +279,22 @@ public void inject(Fragment fragment, Bundle bundle) {
278279
}
279280

280281
@Nullable
281-
public Object go(Context context, Card card, int requestCode, GoCallback callback) {
282-
card.setContext(context);
283-
card.setInterceptorException(null);
284-
card.withString(GoRouter.ROUTER_CURRENT_PATH, card.getPath());
285-
282+
public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {
286283
logger.debug(null, "[go] " + card);
287284
IPretreatmentService pretreatmentService = getService(IPretreatmentService.class);
288285
if (pretreatmentService != null) {
289286
if (!pretreatmentService.onPretreatment(context, card)) {
290287
// 预处理失败,导航取消
291-
logger.debug(null, "[go] PretreatmentService Failure!");
288+
logger.debug(null, "[go] IPretreatmentService Failure!");
292289
return null;
293290
}
294291
} else {
295-
logger.warning(null, "[go] This [PretreatmentService] was not found!");
292+
logger.warning(null, "[go] This [IPretreatmentService] was not found!");
296293
}
297294

295+
card.setContext(context);
296+
card.setInterceptorException(null);
297+
298298
try {
299299
LogisticsCenter.assembleRouteCard(card);
300300
} catch (NoFoundRouteException e) {
@@ -324,7 +324,7 @@ public Object go(Context context, Card card, int requestCode, GoCallback callbac
324324
interceptorService.doInterceptions(card, new InterceptorCallback() {
325325
@Override
326326
public void onContinue(Card card) {
327-
goActivity(context, card, requestCode, callback);
327+
goActivity(context, card, requestCode, activityResultLauncher, callback);
328328
}
329329

330330
@Override
@@ -337,7 +337,7 @@ public void onInterrupt(Card card, @NonNull Throwable exception) {
337337
}
338338
});
339339
} else {
340-
goActivity(context, card, requestCode, callback);
340+
goActivity(context, card, requestCode, activityResultLauncher, callback);
341341
}
342342
break;
343343
case FRAGMENT:
@@ -356,14 +356,14 @@ private void onLost(Context context, Card card, GoCallback callback) {
356356
if (degradeService != null) {
357357
degradeService.onLost(context, card);
358358
} else {
359-
logger.warning(null, "[onLost] This [DegradeService] was not found!");
359+
logger.warning(null, "[onLost] This [IDegradeService] was not found!");
360360
}
361361
}
362362
});
363363
}
364364

365365
@SuppressLint("WrongConstant")
366-
private void goActivity(Context context, Card card, int requestCode, GoCallback callback) {
366+
private void goActivity(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {
367367
Intent intent = new Intent(context, card.getPathClass());
368368

369369
intent.putExtras(card.getExtras());
@@ -383,14 +383,17 @@ private void goActivity(Context context, Card card, int requestCode, GoCallback
383383
}
384384

385385
runInMainThread(() -> {
386+
ActivityOptionsCompat compat = card.getActivityOptionsCompat();
386387
if (requestCode >= 0) {
387388
if (context instanceof Activity) {
388-
ActivityCompat.startActivityForResult((Activity) context, intent, requestCode, card.getOptionsBundle());
389+
ActivityCompat.startActivityForResult((Activity) context, intent, requestCode, compat != null ? compat.toBundle() : null);
389390
} else {
390391
throw new RouterException("Must use [go(activity, ...)] to support [startActivityForResult]!");
391392
}
393+
} else if (activityResultLauncher != null) {
394+
activityResultLauncher.launch(intent, compat);
392395
} else {
393-
ActivityCompat.startActivity(context, intent, card.getOptionsBundle());
396+
ActivityCompat.startActivity(context, intent, compat != null ? compat.toBundle() : null);
394397
}
395398

396399
if ((-1 != card.getEnterAnim() && -1 != card.getExitAnim()) && context instanceof Activity) {
@@ -424,4 +427,41 @@ private Object goFragment(Card card, GoCallback callback) {
424427
}
425428
}
426429

430+
public <T> void registerEvent(FragmentActivity activity, @NonNull Class<T> type, @NonNull Observer<T> observer) {
431+
LogisticsCenter.registerEvent(activity, type, false, observer);
432+
}
433+
434+
public <T> void registerEvent(Fragment fragment, @NonNull Class<T> type, @NonNull Observer<T> observer) {
435+
LogisticsCenter.registerEvent(fragment, type, false, observer);
436+
}
437+
438+
public <T> void registerEventForever(FragmentActivity activity, @NonNull Class<T> type, @NonNull Observer<T> observer) {
439+
LogisticsCenter.registerEvent(activity, type, true, observer);
440+
}
441+
442+
public <T> void registerEventForever(Fragment fragment, @NonNull Class<T> type, @NonNull Observer<T> observer) {
443+
LogisticsCenter.registerEvent(fragment, type, true, observer);
444+
}
445+
446+
public <T> void unRegisterEvent(FragmentActivity activity, @NonNull Class<T> type) {
447+
LogisticsCenter.unRegisterEvent(activity, type, null);
448+
}
449+
450+
public <T> void unRegisterEvent(Fragment fragment, @NonNull Class<T> type) {
451+
LogisticsCenter.unRegisterEvent(fragment, type, null);
452+
}
453+
454+
public <T> void unRegisterEvent(FragmentActivity activity, @NonNull Class<T> type, Observer<T> observer) {
455+
LogisticsCenter.unRegisterEvent(activity, type, observer);
456+
}
457+
458+
public <T> void unRegisterEvent(Fragment fragment, @NonNull Class<T> type, Observer<T> observer) {
459+
LogisticsCenter.unRegisterEvent(fragment, type, observer);
460+
}
461+
462+
public <T> void postEvent(@NonNull String path, @NonNull T value) {
463+
LogisticsCenter.postEvent(path, value);
464+
}
465+
466+
427467
}

GoRouter-Api/src/main/java/com/wyjson/router/core/Constants.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
class Constants {
44

5+
static final String ROUTER_CURRENT_PATH = "go_router_current_path";
6+
static final String ROUTER_RAW_URI = "go_router_raw_uri";
7+
58
static final String GOROUTER_SP_CACHE_KEY = "SP_GOROUTER_CACHE";
69
static final String SEPARATOR = "$$";
710
static final String PACKAGE_NAME = "com.wyjson.router";

GoRouter-Api/src/main/java/com/wyjson/router/core/LogisticsCenter.java

Lines changed: 154 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
package com.wyjson.router.core;
22

3+
import static com.wyjson.router.core.Constants.ROUTER_CURRENT_PATH;
4+
import static com.wyjson.router.core.Constants.ROUTER_RAW_URI;
5+
36
import android.app.Activity;
47
import android.content.Intent;
58
import android.net.Uri;
69
import android.os.Bundle;
10+
import android.os.Handler;
11+
import android.os.Looper;
712

813
import androidx.annotation.NonNull;
914
import androidx.annotation.Nullable;
1015
import androidx.fragment.app.Fragment;
16+
import androidx.lifecycle.Lifecycle;
17+
import androidx.lifecycle.LifecycleEventObserver;
18+
import androidx.lifecycle.LifecycleObserver;
19+
import androidx.lifecycle.LifecycleOwner;
20+
import androidx.lifecycle.MutableLiveData;
21+
import androidx.lifecycle.Observer;
1122

1223
import com.wyjson.router.GoRouter;
1324
import com.wyjson.router.enums.ParamType;
@@ -184,7 +195,7 @@ public static <T> String getRawURI(T target) {
184195
} catch (Exception e) {
185196
throw new RuntimeException("getRawURI() " + e.getMessage());
186197
}
187-
return bundle.getString(GoRouter.ROUTER_RAW_URI);
198+
return bundle.getString(ROUTER_RAW_URI);
188199
}
189200

190201
/**
@@ -195,12 +206,16 @@ public static <T> String getRawURI(T target) {
195206
*/
196207
public static <T> String getCurrentPath(T target) {
197208
Bundle bundle;
198-
try {
199-
bundle = getBundle(target, null, null);
200-
} catch (Exception e) {
201-
throw new RuntimeException("getCurrentPath() " + e.getMessage());
209+
if (target instanceof Bundle) {
210+
bundle = (Bundle) target;
211+
} else {
212+
try {
213+
bundle = getBundle(target, null, null);
214+
} catch (Exception e) {
215+
throw new RuntimeException("getCurrentPath() " + e.getMessage());
216+
}
202217
}
203-
return bundle.getString(GoRouter.ROUTER_CURRENT_PATH);
218+
return bundle.getString(ROUTER_CURRENT_PATH);
204219
}
205220

206221
/**
@@ -220,9 +235,9 @@ public static <T> void inject(T target, Intent intent, Bundle bundle) {
220235
throw new RuntimeException("inject() " + e.getMessage());
221236
}
222237

223-
String path = bundle.getString(GoRouter.ROUTER_CURRENT_PATH);
238+
String path = getCurrentPath(bundle);
224239
if (TextUtils.isEmpty(path)) {
225-
GoRouter.logger.error(null, "[inject] path Parameter is invalid!");
240+
GoRouter.logger.error(null, "[inject] The " + ROUTER_CURRENT_PATH + " parameter was not found in the intent");
226241
return;
227242
}
228243

@@ -298,6 +313,7 @@ public static synchronized void assembleRouteCard(@NonNull Card card) throws NoF
298313
CardMeta cardMeta = getCardMeta(card);
299314
if (cardMeta != null) {
300315
card.setCardMeta(cardMeta.getType(), cardMeta.getPathClass(), cardMeta.getTag());
316+
card.withString(ROUTER_CURRENT_PATH, card.getPath());
301317

302318
Map<String, ParamMeta> paramsType = cardMeta.getParamsType();
303319
Uri rawUri = card.getUri();
@@ -313,7 +329,7 @@ public static synchronized void assembleRouteCard(@NonNull Card card) throws NoF
313329
}
314330
}
315331
// 保存原始uri
316-
card.withString(GoRouter.ROUTER_RAW_URI, rawUri.toString());
332+
card.withString(ROUTER_RAW_URI, rawUri.toString());
317333
}
318334
}
319335
}
@@ -362,4 +378,133 @@ private static void setValue(Card card, ParamType type, String key, String value
362378
}
363379
}
364380

381+
public static <T> void registerEvent(LifecycleOwner owner, @NonNull Class<T> type, boolean isForever, @NonNull Observer<T> observer) {
382+
if (!(owner instanceof Activity) && !(owner instanceof Fragment)) {
383+
/**
384+
* 正常通过api调用是不会走到这里,除非直接调用了此方法才有可能出现这种情况
385+
* 可能是FragmentViewLifecycleOwner类型,需要导包才能直接判断,为了少导入包,就这么写判断吧.
386+
*/
387+
throw new RouterException("The owner can only be an Activity or Fragment");
388+
}
389+
if (type == null) {
390+
throw new RouterException("type cannot be empty!");
391+
}
392+
393+
String path = getCurrentPath(owner);
394+
if (TextUtils.isEmpty(path)) {
395+
GoRouter.logger.error(null, "[registerEvent] The " + ROUTER_CURRENT_PATH + " parameter was not found in the intent");
396+
return;
397+
}
398+
399+
String key = path + "$" + type.getCanonicalName();
400+
MutableLiveData<T> liveData;
401+
if (Warehouse.events.containsKey(key)) {
402+
liveData = Warehouse.events.get(key);
403+
} else {
404+
liveData = new MutableLiveData<>();
405+
Warehouse.events.put(key, liveData);
406+
addLifecycleObserver(owner, getLifecycleObserver(key));
407+
}
408+
if (liveData != null) {
409+
if (isForever) {
410+
liveData.observeForever(observer);
411+
} else {
412+
liveData.observe(owner, observer);
413+
}
414+
} else {
415+
GoRouter.logger.error(null, "[registerEvent] LiveData is empty??");
416+
}
417+
}
418+
419+
public static <T> void unRegisterEvent(LifecycleOwner owner, @NonNull Class<T> type, Observer<T> observer) {
420+
if (type == null) {
421+
throw new RouterException("type cannot be empty!");
422+
}
423+
424+
String path = getCurrentPath(owner);
425+
if (TextUtils.isEmpty(path)) {
426+
GoRouter.logger.error(null, "[registerEvent] The " + ROUTER_CURRENT_PATH + " parameter was not found in the intent");
427+
return;
428+
}
429+
430+
String key = path + "$" + type.getCanonicalName();
431+
if (Warehouse.events.containsKey(key)) {
432+
MutableLiveData<T> liveData = Warehouse.events.get(key);
433+
if (liveData != null) {
434+
if (observer != null) {
435+
liveData.removeObserver(observer);
436+
} else {
437+
liveData.removeObservers(owner);
438+
}
439+
if (!liveData.hasObservers()) {
440+
Warehouse.events.remove(key);
441+
}
442+
}
443+
} else {
444+
GoRouter.logger.warning(null, "[unRegisterEvent] No observer was found for this event");
445+
}
446+
}
447+
448+
/**
449+
* 页面销毁时删除当前页面注册的事件
450+
*
451+
* @param key
452+
* @param <T>
453+
* @return
454+
*/
455+
@NonNull
456+
private static <T> LifecycleEventObserver getLifecycleObserver(String key) {
457+
return new LifecycleEventObserver() {
458+
@Override
459+
public void onStateChanged(@NonNull LifecycleOwner owner, @NonNull Lifecycle.Event event) {
460+
if (event == Lifecycle.Event.ON_DESTROY) {
461+
owner.getLifecycle().removeObserver(this);
462+
if (Warehouse.events.containsKey(key)) {
463+
MutableLiveData<T> liveData = Warehouse.events.get(key);
464+
if (liveData != null && liveData.hasObservers()) {
465+
liveData.removeObservers(owner);
466+
}
467+
Warehouse.events.remove(key);
468+
}
469+
}
470+
}
471+
};
472+
}
473+
474+
private static void addLifecycleObserver(final LifecycleOwner lifecycleOwner, @NonNull LifecycleObserver lifecycleObserver) {
475+
if (lifecycleOwner == null)
476+
return;
477+
Runnable runnable = () -> lifecycleOwner.getLifecycle().addObserver(lifecycleObserver);
478+
if (Looper.myLooper() == Looper.getMainLooper()) {
479+
runnable.run();
480+
} else {
481+
new Handler(Looper.getMainLooper()).post(runnable);
482+
}
483+
}
484+
485+
public static <T> void postEvent(@NonNull String path, @NonNull T value) {
486+
if (TextUtils.isEmpty(path)) {
487+
throw new RouterException("path Parameter is invalid!");
488+
}
489+
if (value == null) {
490+
throw new RouterException("value cannot be empty!");
491+
}
492+
String key = path + "$" + value.getClass().getCanonicalName();
493+
if (Warehouse.events.containsKey(key)) {
494+
MutableLiveData<T> liveData = Warehouse.events.get(key);
495+
if (liveData != null) {
496+
if (Looper.myLooper() == Looper.getMainLooper()) {
497+
liveData.setValue(value);
498+
} else {
499+
liveData.postValue(value);
500+
}
501+
} else {
502+
GoRouter.logger.error(null, "[postEvent] LiveData is empty??");
503+
}
504+
} else {
505+
GoRouter.logger.warning(null, "[postEvent] No observer was found for this event");
506+
}
507+
}
508+
509+
365510
}

0 commit comments

Comments
 (0)