- Notifications
You must be signed in to change notification settings - Fork3
ArTemmey/react-native-android-navigation
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Let your application feel at ease.
React Native Android Navigation is the new way to integrate JavaScript and Java/Kotlin inside React Native.With it's help you can easily handle native window or background task in your project and also interact with other applications.
Native Android navigation is made up of two main parts:
Navigation methods, available inside the native window —
Activity— and inside the background task worker —Service;Object with the navigation data —
Intent, which is passed into the navigation methods to direct the router. It's also transferred to the destination.
Based on this, React Native Android Navigation has two classes for usage:
AndroidNavigator— class that wraps all the navigation methods as static properties;Intent— native Intent wrapper.
Simple example:
import{AndroidNavigator,Intent}from'react-native-android-navigation';constintent=newIntent();intent.setClassName('your.package.name.YourActivity');AndroidNavigator.startActivity(intent);
"your.package.name" is the path from<YourProject>/android/app/src/main/java to the directory where your Activity class is located.
yarn add react-native-android-navigation
or
npm install --save react-native-android-navigation
react-native link react-native-android-navigation
- Open
<YourProject>/android/settings.gradleand add the following:
include ':react-native-android-navigation' project(':react-native-android-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-navigation/android')- Open
<YourProject>/android/app/build.gradleand add inside the dependencies block:
compile project(':react-native-android-navigation')- Open
<YourProject>/android/app/src/main/java/package.name/MainApplication.java:
- Add
import com.navigation.NavigationPackage; - Add
new NavigationPackage()to the list returned bygetPackages()method
Intent has four methods for initialization. Call them separately or in combination with each other:
setClassName(className: string): IntentUse it separately if the target Activity is inside your application. Combine with
setPackageNameif the target Activity is inside another application.setPackageName(packageName: string): IntentUse it separately to get the launcher Intent for the target package. Combine with
setClassNameif you need to start a certain Activity from the target package.setAction(action: string): IntentRepresents Android Intent method
setAction. Note that JS Intent class has all the default Android Intent actions as static properties, so use them them the same way as in Android:intent.setAction(Intent.ACTION_MAIN).setCustomServiceEventName(eventName: string): IntentUse it separately to startyour custom Service. Combine with
setPackageNameif the target Service is inside another application.
Intent allows you to pass extra data of any type.
Putting extras is done in the same way as in Android, with the following methods:
putExtra(key: string, extra: any): IntentputExtras(extras: Object): Intent
Example:
intent.putExtra("key1","Hello world!").putExtras(//New data will be added to the existing{key2:25.001,key3:["pass array",true,12345],key4:{key1:"object as well",key2:69.999}});
On Java side, extras can be obtained as usual.For primitives and strings usegetBooleanExtra,getIntExtra,getDoubleExtra,getStringExtra.For arrays and objects usegetSerializableExtra and cast the result toList orMap respectively. Then if needed cast each their child to its class.
Example:
StringhelloWorld =intent.getStringExtra("key1"));Listlist = (List)intent.getSerializableExtra("key3");booleanb = (Boolean)list.get(1);Mapmap = (Map)intent.getSerializableExtra("key4");doubled = (Double)map.get("key2");
On JS side, just use the following methods:
getExtra(key: string): anygetExtras(): Object
removeExtra(key: string): voidreplaceExtras(extras: Object): IntenthasExtra(key: string): boolean
To deal with categories and flags the same methods are used as in Android:
addCategory(category: string): IntentremoveCategory(category: string): voidgetCategories(): string[]hasCategory(category: string): booleanaddFlags(flags: number): IntentsetFlags(flags: number): IntentgetFlags(): number[]removeFlags(flags: number): void
Like the actions, all the default Android Intent categories and flags are declared in JS Intent class as static properties, so use them the same way as in Android.
Example:
intent.addCategory(Intent.CATEGORY_DEFAULT).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
To start new Activity, use the same methods as in Android:
static startActivity(intent: Intent): Promise<void>static startActivityForResult(intent: Intent, requestCode: number): Promise<void>Use it to get the data you need from the target Activity after it's finished.
requestCodecan be any integer.
To get the result, add event listener for the correspondingActivityEventType:
export type ActivityResultListener = (requestCode: number, resultCode: number, data: Intent | null) => void
Example:
constmyOnResult=(requestCode,resultCode,data)=>{console.log(data.getExtras().key1);};AndroidNavigator.addEventListener(ActivityEventType.ACTIVITY_RESULT,myOnResult);//myOnResult will be called each time Activity result is received
React Native Android Navigation allows you to pass any data from native side on back press event.
On Java side, open file<YourProject>/android/app/src/main/java/your.package.name/MainActivity.java:
- Add
import com.navigation.NavigationModule; - Add inside the Activity class:
@OverridepublicvoidonBackPressed() {NavigationModule.onBackPressed("My data",123);//pass rest parameters}
On JS side, add event listener for the correspondingActivityEventType:
export type BackPressListener = (...data: any) => void
Example:
constmyOnBackPressed=(myData,oneTwoThree)=>{console.log(myData);};AndroidNavigator.addEventListener(ActivityEventType.BACK_PRESSED,myOnBackPressed);//myOnBackPressed will be called each time back button is pressed
static currentActivityIsRunning(): Promise<boolean>Checks if your app has any running Activity.
static getIntent(): Promise<Intent>Gets the Intent with which Activity was started.
setResult(resultCode: number, data?: Intent): Promise<void>Use it if Activity was started for result.Possible values of
resultCodeare included in AndroidNavigator as static properties:RESULT_CANCELED = 0,RESULT_FIRST_USER = 1,RESULT_OK = -1finish(): Promise<void>Closes current Activity.
To start Service, use the same method as in Android:
startService(intent: Intent): Promise<void>
To add your custom task, add it's event listener:
export type CustomServiceEventListener = (extras: Object) => void
and then start it withstartService method, passing Intent, initialized withsetCustomServiceEventName.
Example:
constmyServiceListener=(eventExtras)=>{console.log(eventExtras.myData);};AndroidNavigator.addEventListener("myService",myServiceListener);constintent=newIntent();intent.setCustomServiceEventName("myService");intent.putExtra("myData","Hello world!");AndroidNavigator.startService(intent);
The following errors can be thrown while using AndroidNavigator methods:
exportclassNavigationErrorextendsError{constructor(message:NavigationErrorMessage){}}
exportenumNavigationErrorMessage{TARGET_CLASS_NOT_FOUND="TARGET_CLASS_NOT_FOUND",TARGET_PACKAGE_NOT_FOUND="TARGET_PACKAGE_NOT_FOUND",TARGET_CLASS_NOT_EXPORTED="TARGET_CLASS_NOT_EXPORTED"}
exportclassNoActivityErrorextendsError{constructor(message:string){}}
To catch them, addcatch block on any Promise returned by AndroidNavigator method.
Example:
AndroidNavigator.startActivity(intent).catch((e)=>{console.log(e.message);});
About
True Android native navigation for React Native apps
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.