getting variable from native module in sub class - android

I have LibModule.java set as native module in reactnative
.....
class LibModule extends ReactContextBaseJavaModule {
boolean readingMyKad = false;
....
public void read_mykad_main() {
clear_results();
pre_card_status = -1;
new readMyKad(reactContext).execute();
}
public static class readMyKad extends AsyncTask<Void, Void, Integer> {
CountDownTimer readMyKadCdt;
readMyKad readMyKadObject;
private WeakReference<ReactApplicationContext> activityReference;
readMyKad(ReactApplicationContext reactContext) {
activityReference = new WeakReference<>(reactContext);
}
protected void onPreExecute() {
readMyKadObject = this;
readMyKadCdt = new CountDownTimer(25000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if ( activityReference.get().readingMyKad ) {
try {
activityReference.get().readingMyKad = false;
if (readMyKadObject.getStatus() == AsyncTask.Status.RUNNING) {
boolean bret = readMyKadObject.cancel(true);
Log.e(TAG,"readMyKadAsyncTask Timeout, cancel: " + bret);
}
} catch (Exception ignored) {
}
}
}
};
readMyKadCdt.start();
}
...............
but in class readMyKad, i need to get variables from my main module LibModule such as activityReference.get().readingMyKad.
not just get the variable but also set and call function from LibModule. how can i do that because LibModule is not an activity.
im sorry for my english and the title.

Related

Here map sdk to react native component

I have a problem with Here map sdk. Im trying to create a compmonent from native side and call from react native side. But i'm having this problem. I cant get the map initilize.
ScreenShot
I get this error from emulator.
These are my codes :
HereMapView.java :
public class HereMapView extends MapViewLite {
private static final String TAG = HereMapView.class.getSimpleName();
private MapViewLite mapView;
public HereMapView(ThemedReactContext reactContext) {
super(reactContext);
loadMapScene();
}
private void loadMapScene() {
// Load a scene from the SDK to render the map with a map style.
mapView.getMapScene().loadScene(MapStyle.NORMAL_DAY, new MapScene.LoadSceneCallback() {
#Override
public void onLoadScene(#Nullable MapScene.ErrorCode errorCode) {
if (errorCode == null) {
mapView.getCamera().setTarget(new GeoCoordinates(52.530932, 13.384915));
mapView.getCamera().setZoomLevel(14);
} else {
Log.d(TAG, "onLoadScene failed: " + errorCode.toString());
}
}
});
}
#Override
public void onPause() {
super.onPause();
this.onPause();
}
#Override
public void onResume() {
super.onResume();
this.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
this.onDestroy();
}
}
HereMapManager.java :
public class HereMapManager extends ViewGroupManager<HereMapView> {
private static final String TAG = HereMapManager.class.getSimpleName();
static final String REACT_CLASS = "HereMapView";
public Activity activity;
public HereMapManager(Activity activity){
this.activity = activity;
}
#Override
public String getName() {
return REACT_CLASS;
}
#Override
protected HereMapView createViewInstance(ThemedReactContext reactContext) {
return new HereMapView(reactContext);
}
}
HereMapModule.java :
public class HereMapModule extends ReactContextBaseJavaModule {
private static final String TAG = HereMapModule.class.getSimpleName();
HereMapModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "HereMapView";
}
public Activity getActivity() {
return getCurrentActivity();
}
public static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
HereMapPackage :
public class HereMapPackage implements ReactPackage {
protected Activity activity;
public HereMapPackage() {
}
public HereMapPackage(Activity activity) {
this.activity = activity;
} // backwards compatibility
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new HereMapModule(reactContext));
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
//HereMapManager mapManager = new HereMapManager(reactContext);
HereMapManager mapManager = new HereMapManager(this.activity);
return Arrays.<ViewManager>asList(mapManager);
}
}
then i adding the package to :
MainAplication.java :
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new HereMapPackage());
return packages;
}
with this function.
And then i call from react native side with this code :
App.js :
const HereMapView = requireNativeComponent('HereMapView');
const App: () => React$Node = () => {
return (
<SafeAreaView style={styles.screen}>
<View style={styles.screen}>
<HereMapView style={{flex : 1}} />
</View>
</SafeAreaView>
);
};
Can you help me please? Im stuck over a 2 week in this.

Xposed - I can print inner class methods, but method hooking doesn't work

I'm trying to hook a method in inner class, but nothing happen, while I can print all the methods of that class.
All of the logs printed except which is in the replaceHookedMethod.
public class Keyguard implements IXposedHookLoadPackage {
#Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.keyguard"))
return;
XposedBridge.log("we are in keyguard!");
Class HwClockView = XposedHelpers.findClass("com.android.keyguard.AbsClockView$HwClockView",
lpparam.classLoader);
for (Method m : HwClockView.getDeclaredMethods()) {
XposedBridge.log("method: " + m.getName());
}
XposedHelpers.findAndHookMethod(HwClockView, "getDateString",
TimeZone.class, new XC_MethodReplacement() {
#Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("we are in getDateString!");
return String.format("%s", Utils.getPersianDateShort());
}
});
}
Update:
After second comment changed code to this, but same as before nothing happens:
public class Keyguard implements IXposedHookLoadPackage {
#Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) {
if (!lpparam.packageName.equals("com.android.keyguard"))
return;
XposedBridge.log("we are in keyguard!");
Class HwClockView = XposedHelpers.findClass("com.android.keyguard.AbsClockView$HwClockView",
lpparam.classLoader);
for (Method m : HwClockView.getDeclaredMethods()) {
XposedBridge.log("method: " + m.getName());
if ("getDateString".equalsIgnoreCase(m.getName())) {
XposedBridge.hookMethod(m, new XC_MethodReplacement() {
#Override
protected Object replaceHookedMethod(MethodHookParam param) {
XposedBridge.log("we are in getDateString!");
return String.format("%s", Utils.getPersianDateShort());
}
});
}
}
}
Target class:
public class AbsClockView extends RelativeLayout {
protected Calendar mCalendar;
private HwCustKeyguardStatusViewEx mCustKeyguardStatusViewEx;
protected TextView mDateView;
protected TextView mDescriptionView;
protected Factory mFactory;
protected final AtomicBoolean mFixedTimeZone;
protected FrameLayout mTimeParent;
protected TextView mTimeView;
public interface Factory {
void refreshDate();
void setHwDateFormat();
void updateHwTimeStyle();
}
private class HwClockView implements Factory {
protected Context mContext;
public HwClockView(Context context) {
...
}
private CharSequence getDateString(TimeZone timeZone) {
return someString;
}
}
public AbsClockView(Context context) {
this(context, null);
}
}

Android: How to handle when Realm finishes sync?

I want to start (on background) sync with Realm Object Server when launching my Android app. And after data was successfully downloaded I want to show toast.
How I can do this? What method do I need to use?
Thanks.
I have not tried this but it should work.
private void setRealmDefaultConfiguration(SyncUser syncUser, String realmURL) {
SyncConfiguration config = new SyncConfiguration.Builder(syncUser, realmURL)
.waitForInitialRemoteData()
.build();
Realm.setDefaultConfiguration(config);
}
public abstract class BaseActivity extends Activity {
private static boolean firstInit = true;
protected Realm realm = null;
#Override
public void onCreate(Bundle bundle) {
final boolean shouldShowToast;
if(firstInit) {
firstInit = false;
shouldShowToast = true;
} else {
shouldShowToast = false;
}
super.onCreate(bundle);
Realm.getInstanceAsync(Realm.getDefaultConfiguration(), new Realm.Callback() {
#Override
public void onSuccess(Realm realm) {
if(isChangingConfigurations() || isFinishing()) {
realm.close();
} else {
BaseActivity.this.realm = realm;
onRealmLoaded(realm);
}
if(shouldShowToast) {
Toast.makeText(BaseActivity.this, R.string.data.loaded, Toast.LENGTH_LONG).show();
}
}
#Override
public void onError(Throwable throwable) {
// boop
}
});
}
protected void onRealmLoaded(Realm realm) {
// override this if needed
}
}

Android comunicate between library and app

I'm creating a library in Android and I want to pass some values (strings) from the library to the app that is using the library after some events. The app that uses the library has only one screen to display the strings sent by the library.
My app has a MainActivity that will populate an listView with the events received by the library.
It also have an MyApp that extends Application.
Here I'm doing this:
public class MyApp extends Application{
private static MyApp sMyApp;
public MyApp() {
}
#Override
public void onCreate() {
super.onCreate();
sMyApp= this;
MyLibrary.getInstance().setApplication(sMyApp);
}
public static MyApp getInstance() {
return sMyApp;
}
}
In my library:
public class MyLibrary {
private static MyLibrary sInstance = new MyLibrary();
private Application mMyApp;
public static MyLibrary getInstance() {
return sInstance;
}
private MyLibrary() {
}
public void setApplication(Application myApp) {
mMyApp = myApp;
}
public void sendEventMessage(String message) {
mMyApp.setEvent(message);
}
}
I've tried to implement an interface in MainActivity so that mMyApp.setEvent(message); could send a message that MainActivity could receive but with no success.
How can I achieve what I pretend?
You could try callback as this sample:
Firstly, declare your callback inside library
public interface ILibrary {
public void onStart(String msg);
public void onProcess(String msg);
public void onFish(String msg);}
public class SDK {
private static final String START = "I'm started";
private static final String PROCESSING = "I'm running";
private static final String STOP = "I'm done";
private ILibrary mCallback;
// Make it easy for demo
public SDK(ILibrary callback) {
mCallback = callback;
}
public void start() {
mCallback.onStart(START);
}
public void process() {
mCallback.onProcess(PROCESSING);
}
public void stop() {
mCallback.onFish(STOP);
}}
And then do something like that:
SDK sdk = new SDK(new ILibrary() {
#Override
public void onStart(String msg) {
Log.d("TAG", msg);
}
#Override
public void onProcess(String msg) {
Log.d("TAG", msg);
}
#Override
public void onFish(String msg) {
Log.d("TAG", msg);
}
});
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
sdk.process();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
sdk.stop();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
sdk.start();
}
};
asyncTask.execute();

How to custom Retrofit with AsyncTask?

I use Retrofit. Sometime I want integrate with AsyncTask for some purpose like Dialog Loading...
Here is my way:
public class RetrofitAsyncTask<T extends ResponseModel> {
public interface OnCompleteListener<T extends ResponseModel> {
public void onComplete(T t);
public void onError(Exception e);
}
public interface JsonConverter<T extends ResponseModel> {
public T getModel();
}
protected OnCompleteListener<T> onCompleteListener = null;
protected JsonConverter<T> jsonConverter;
protected ProgressDialog progressDialog;
protected int requestCode = Integer.MIN_VALUE;
public static RetrofitAsyncTask newInstance() {
return new RetrofitAsyncTask();
}
public RetrofitAsyncTask setOnCompleteListener(OnCompleteListener<T> l) {
onCompleteListener = l;
return this;
}
public RetrofitAsyncTask setJsonConverter(JsonConverter<T> converter) {
jsonConverter = converter;
return this;
}
public RetrofitAsyncTask setProgressDialog(ProgressDialog dlg) {
progressDialog = dlg;
return this;
}
public RetrofitAsyncTask setRequestCode(int reqCode) {
requestCode = reqCode;
return this;
}
public void execute() {
new AsyncTask<Void, Void, Exception>() {
private T result;
#Override
protected ProgressDialog getDialogRunOnPreStart() {
/** Retrun dialog will display. Will process on onPre & onPost. But current I will ignore it.**/
return progressDialog;
}
#Override
protected Exception doInBackground(Void... params) {
if (jsonConverter == null) {
return null;
}
try {
result = jsonConverter.getModel();
result.setRequestCode(requestCode);
} catch (Exception e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception e) {
if (onCompleteListener != null) {
if (e != null || result == null) {
onCompleteListener.onError(e);
} else {
onCompleteListener.onComplete(result);
}
}
}
}.execute();
}
}
In this case class ResponseModel is Empty class.
public class ResponseModel {/** You will custom some filed default here **/}
Next you will define some Service Api.... look like:
public interface MyService {
#GET("/path")
public User getUserInfo(....);
}
(Notes class User Must be extend from ResponseModel).
Then you will custom some RetrofitAdapter...
Finally to use RetrofitAsyncTask you will do something like:
RetrofitAsyncTask.newInstance()
.setJsonConverter(
new RetrofitAsyncTask.JsonConverter<User>() {
#Override
public User getModel() {
return MyService.getUser(...);
}
}
)
.setOnCompleteListener(this)
.setRequestCode(requestCode)
.execute();
That's way I done. But current I feel it not good.
(setJsonConverter get much line :|, If you have any idea to make it better & shorter please comment ! Thanks so so much !)

Categories

Resources