Why BiometricPrompt API in Xamarin Android doesn't contain onAuthenticationError Callback - xamarin.android

In Android Studios BiometricPrompt API contains a callback named onAuthenticationError which gets triggered when the user touch outside the BiometricPrompt dialog and once a user tries to input an invalid Biometric to the device. But the BiometricPrompt API available in Xamarin.Android platform doesn't provide onAuthenticationError callback.
I created an android application using Android Studios to check BiometricPrompt API there I could access the callback named onAuthenticationError. Then I deployed the application to a device and debugged the application. The above mentioned callback got triggered when I touched any area outside the BiometricPrompt dialog and it also got triggered every time I provided BiometricPrompt with a invalid input more than 5 times.
Then I tried developing the same application in Xamain.Android and there I was unable to find any callback named onAuthenticationError. When I deployed and tested the application in a device as the above-mentioned callback was not available I couldn't handle the 2 scenarios
where when the user touches any area outside the BiometricPrompt dialog and when user provides the BiometricPrompt with an invalid input more than 5 times.
My Native android code snippet.
#RequiresApi(api = Build.VERSION_CODES.P)
private BiometricPrompt.AuthenticationCallback getAuthenticationCallback() {
return new BiometricPrompt.AuthenticationCallback() {
#Override
** public void onAuthenticationError(int errorCode,
CharSequence errString) {
notifyUser("Authentication error: " + errString);
super.onAuthenticationError(errorCode, errString);
}**
#Override
public void onAuthenticationHelp(int helpCode,
CharSequence helpString) {
super.onAuthenticationHelp(helpCode, helpString);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
#Override
public void onAuthenticationSucceeded(
BiometricPrompt.AuthenticationResult result) {
notifyUser("Authentication Succeeded");
super.onAuthenticationSucceeded(result);
}
};
}
My Xamarin.Android code snippet
public class BiometricAuthCallBacks : BiometricPrompt.AuthenticationCallback
{
public TaskCompletionSource<LocalAuthStatus> promise = new TaskCompletionSource<LocalAuthStatus>();
private int failCount;
public override void OnAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result)
{
base.OnAuthenticationSucceeded(result);
promise.TrySetResult(LocalAuthStatus.Success);
//Success(result);
}
public override void OnAuthenticationFailed()
{
base.OnAuthenticationFailed();
failCount++;
if (failCount>=5)
{
promise.TrySetResult(LocalAuthStatus.Fail);
}
//Failed();
}
public override void OnAuthenticationHelp([GeneratedEnum] BiometricAcquiredStatus helpCode, ICharSequence helpString)
{
base.OnAuthenticationHelp(helpCode, helpString);
promise.TrySetResult(LocalAuthStatus.Error);
//Help(helpCode, helpString);
}
}
My Question is why can't I access onAuthenticationError callback from Xamarin.Android platform and how can I resolve this?

Related

Xamarin MvvmCross: iOS how to monitor the app has move to foreground/background

I have an MvvmCross application, and I am using the MvvmCross ViewModel Lifecycle functions to realize
certain actions when the view appears, moves to background, and moves to foreground:
public override async void ViewAppeared()
public override async void ViewAppearing()
public override void ViewDisappearing()
public override void ViewDisappeared()
public override void ViewDestroy(bool viewFinishing)
Those functions work great in my Android device.
But for iOS they do not get fired when the application moves to background or to foreground
(although, except for ViewDestroy, they fire when navigating between the screens in the app in iOS)
1)Is that the intended behavior, or I am missing something?
2)If so, what is the approach we have to follow, when there are actions that we need to do when the app moves to foreground/background (like stopping timers)?
Should we maybe have two implementations one for android, and one for ios? I also tried the ViewDidDisappear method in the MvxBaseViewController,
still it is not activated when the app moves to background. There is a way in Xamarin/MvvmCross to hook into the native ios applicationDidEnterBackground?
Edit:
I have tried Ranjit´s answer, but it seems to be a problem subscribing to the message. Here is my test code:
AppDelegate.cs:
public override void DidEnterBackground(UIApplication application)
{
base.DidEnterBackground(application);
var message = new LocationMessage(
this,
34
);
_messenger = Mvx.IoCProvider.Resolve<IMvxMessenger>();
_messenger.Publish(message);
}
Base class:
public abstract class GenericMvxViewModel : MvxViewModel
{
private IMvxMessenger _messenger;
protected GenericMvxViewModel()
{
// other stuff
_messenger = Mvx.IoCProvider.Resolve<IMvxMessenger>();
_messenger.Subscribe<LocationMessage>(OnLocationMessage);
}
protected virtual void OnLocationMessage(LocationMessage locationMessage){}
}
ViewModel:
public class MyClassViewModel : GenericMvxViewModel
{
protected override void OnLocationMessage(LocationMessage locationMessage)
{
Debug.WriteLine(locationMessage.Lat);
}
}
The message is published in the AppDelegate.cs, but the OnLocationMessage method in the viewmodel is never executed.
Also I was wondering how to unsubscribe properly the message. ViewDestroy seems the most natural place, but as mentioned before it is never called on iOS
Your code should work. I am using same kind of function in my app it was working fine
GenericMvxViewModel Code
private MvxSubscriptionToken _locationEventToken;
public override void ViewAppeared()
{
SubscribeBaseLocationEvent();
base.ViewAppeared();
}
public override void ViewDisappeared()
{
if (StaticStorage.IsApplicationInForeground)
{
UnSubscribeBaseLocationEvent();
}
base.ViewDisappeared();
}
public void SubscribeBaseLocationEvent()
{
if (_locationEventToken == null)
{
_locationEventToken = Messenger.Subscribe<LocationMessage>(OnLocationMessage);
}
}
public void UnSubscribeBaseLocationEvent()
{
if (_locationEventToken != null)
{
Messenger.Unsubscribe<LocationMessage>(_locationEventToken);
_locationEventToken = null;
}
}
AppDelegate Code
public override void DidEnterBackground(UIApplication application)
{
base.DidEnterBackground(application);
StaticStorage.IsApplicationInForeground = false;
_messenger.Publish(new LocationMessage( this, 34 ));
}
public override void WillEnterForeground(UIApplication application)
{
StaticStorage.IsApplicationInForeground = true;
}
Android
protected override void OnResume()
{
StaticStorage.IsApplicationInForeground = true;
base.OnResume();
}
protected override void OnStop()
{
StaticStorage.IsApplicationInForeground = false;
base.OnStart();
}
When application is moving from one view to other view, we need to unsubscribe the event. But not when application moves to background. So, IsApplicationInForeground flag will help to solve this issue for android. Because for android when application goes to background ViewDisappeared will be called.
In my case. I have one common activity which holds remaining all views of fragment. So, I have added this code in common activity. Not sure in your case how you are using. But implementation will be similar.

Vaadin Grid middle mouse click

I'm trying to emulate normal browser behaviour in my vaadin grid, which includes middle mouse click to open in a new tab:
addItemClickListener(e -> {
boolean newTab = e.getMouseEventDetails().getButton() == MouseEventDetails.MouseButton.MIDDLE || e.getMouseEventDetails().isCtrlKey();
//open in window or new tab
});
However, the middle mouse button is not registered by vaadin. How could I get this to work?
That feature was included in vaadin-grid (which goes into Vaadin 10) and will not work in Vaadin 8.
For Vaadin 8, you can either intercept the event with some client-side extension, or use a ComponentRenderer for adding a Panel to each component (which works, but is not ideal because it degrades performance):
grid.addColumn(item->{
Panel p = new Panel(item.getName());
p.setStyleName(ValoTheme.PANEL_BORDERLESS);
p.addClickListener(ev->{
System.out.println(ev.getButtonName());
});
return p;
}).setRenderer(new ComponentRenderer());
A client-side extension, on the other hand, allows listening to javascript events (such as MouseEvent) and triggering a server event in response. Creating a extension is quite a complex topic (since it uses a part of the API that is normally hidden from the developer) but it allows direct access to rendered DOM, which is not possible otherwise.
The following resources from the documentation may give you a starting point:
Creating a component extension (which describes a simple extension with Java code only) and Integrating JavaScript Components and Extension (which explains how to add native JavaScript code to your extension).
How I solved the problem in my specific case:
Server side:
public class MyGrid<T> extends Grid<T> {
public MyGrid(String caption, DataProvider<T, ?> dataProvider) {
super(caption, dataProvider);
MiddleClickExtension.extend(this);
}
public static class MiddleClickExtension<T> extends AbstractGridExtension<T> {
private MiddleClickExtension(MyGrid<T> grid) {
super.extend(grid);
registerRpc((rowKey, columnInternalId, details) -> grid.fireEvent(
new ItemClick<>(grid, grid.getColumnByInternalId(columnInternalId), grid.getDataCommunicator().getKeyMapper().get(rowKey), details)),
MiddleClickGridExtensionConnector.Rpc.class);
}
public static void extend(MyGrid<?> grid) {
new MiddleClickExtension<>(grid);
}
#Override
public void generateData(Object item, JsonObject jsonObject) {
}
#Override
public void destroyData(Object item) {
}
#Override
public void destroyAllData() {
}
#Override
public void refreshData(Object item) {
}
}
}
Client side:
#Connect(MyGrid.MiddleClickExtension.class)
public class MiddleClickGridExtensionConnector extends AbstractExtensionConnector {
#Override
protected void extend(ServerConnector target) {
getParent().getWidget().addDomHandler(event -> {
if (event.getNativeButton() == NativeEvent.BUTTON_MIDDLE) {
event.preventDefault();
CellReference<JsonObject> cell = getParent().getWidget().getEventCell();
getRpcProxy(Rpc.class).middleClick(cell.getRow().getString(DataCommunicatorConstants.KEY), getParent().getColumnId(cell.getColumn()),
MouseEventDetailsBuilder.buildMouseEventDetails(event.getNativeEvent(), event.getRelativeElement()));
}
}, MouseDownEvent.getType());
}
#Override
public GridConnector getParent() {
return (GridConnector) super.getParent();
}
public interface Rpc extends ServerRpc {
void middleClick(String rowKey, String columnInternalId, MouseEventDetails details);
}
}

Twitter Login crash

I am developing an app with Twitter login. When I am checking Fabric, it doesn't contain Twitter login as it's no longer available via Fabric, so I am trying to implement it using Twitter Kit (Twitter Kit Link).
I have installed Twitter Kit on my app, when I am trying to run the app it crashes on
Twitter.sharedInstance().startWithConsumerKey(<key>, consumerSecret: <secret>)
Error: terminating with uncaught exception of type NSException
Any solutions...
try this code
add this gradle line in you project
compile 'com.twitter.sdk.android:twitter:3.0.0'
Write in your Activity/Fragment
//Your Custom Button
private ivTwitter;
//Twitter Login Button
private TwitterLoginButton ivTwitterMain;
//init twitter
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Const.CONSUMER_KEY, Const.CONSUMER_SECRET))
.debug(false)
.build();
Twitter.initialize(config);
//find your button
ivTwitter = (ImageView) findViewById(R.id.ivTwitter);
ivTwitterMain = (TwitterLoginButton)findViewById(R.id.ivTwitterMain);
//twitter login callback
ivTwitterMain.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
getTwitterUserProfile(session);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
Log.d(Const.FRAGMENT_REGISTER, exception.getMessage());
}
});
getTwitterUserProfile code
private void getTwitterUserProfile(TwitterSession session) {
AccountService accountService = new TwitterApiClient(session).getAccountService();
Call<User> callback = accountService.verifyCredentials(true, true, true);
callback.clone().enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("NAME ", result.data.name);
Log.d("EMAIL", result.data.email);
Log.d("PICTURE ", result.data.profileImageUrl);
}
#Override
public void failure(TwitterException exception) {
}
});
}
at last generate Click event of custom button
ivTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//twitter login button
ivTwitterMain.performClick();
}
});
I'm assuming that you have already read the twitter official documentation about "Installation" of the TwitterKit in iOS app. I had such experience and the only thing that worked and wasn't in the documentation was this:
In your Info.plist file make sure that "twitterkit-yourAppKey" in
your CFBundleURLSchemes is Item 0.
I've answered this here. Hope it helps you :)

Not able to receive onNext and onComplete call on subscribed mono

I was trying reactor library and I'm not able to figure out why below mono never return back with onNext or onComplete call. I think I missing very trivial thing. Here's a sample code.
MyServiceService service = new MyServiceService();
service.save("id")
.map(myUserMono -> new MyUser(myUserMono.getName().toUpperCase(), myUserMono.getId().toUpperCase()))
.subscribe(new Subscriber<MyUser>() {
#Override
public void onSubscribe(Subscription s) {
System.out.println("Subscribed!" + Thread.currentThread().getName());
}
#Override
public void onNext(MyUser myUser) {
System.out.println("OnNext on thread " + Thread.currentThread().getName());
}
#Override
public void onError(Throwable t) {
System.out.println("onError!" + Thread.currentThread().getName());
}
#Override
public void onComplete() {
System.out.println("onCompleted!" + Thread.currentThread().getName());
}
});
}
private static class MyServiceService {
private Repository myRepo = new Repository();
public Mono<MyUser> save(String userId) {
return myRepo.save(userId);
}
}
private static class Repository {
public Mono<MyUser> save(String userId) {
return Mono.create(myUserMonoSink -> {
Future<MyUser> submit = exe.submit(() -> this.blockingMethod(userId));
ListenableFuture<MyUser> myUserListenableFuture = JdkFutureAdapters.listenInPoolThread(submit);
Futures.addCallback(myUserListenableFuture, new FutureCallback<MyUser>() {
#Override
public void onSuccess(MyUser result) {
myUserMonoSink.success(result);
}
#Override
public void onFailure(Throwable t) {
myUserMonoSink.error(t);
}
});
});
}
private MyUser blockingMethod(String userId) throws InterruptedException {
Thread.sleep(5000);
return new MyUser("blocking", userId);
}
}
Above code only prints Subcribed!main. What I'm not able to figure out is why that future callback is not pushing values through myUserMonoSink.success
The important thing to keep in mind is that a Flux or Mono is asynchronous, most of the time.
Once you subscribe, the asynchronous processing of saving the user starts in the executor, but execution continues in your main code after .subscribe(...).
So the main thread exits, terminating your test before anything was pushed to the Mono.
[sidebar]: when is it ever synchronous?
When the source of data is a Flux/Mono synchronous factory method. BUT with the added pre-requisite that the rest of the chain of operators doesn't switch execution context. That could happen either explicitly (you use a publishOn or subscribeOn operator) or implicitly (some operators like time-related ones, eg. delayElements, run on a separate Scheduler).
Simply put, your source is ran in the ExecutorService thread of exe, so the Mono is indeed asynchronous. Your snippet on the other hand is ran on main.
How to fix the issue
To observe the correct behavior of Mono in an experiment (as opposed to fully async code in production), several possibilities are available:
keep subscribe with system.out.printlns, but add a new CountDownLatch(1) that is .countDown() inside onComplete and onError. await on the countdown latch after the subscribe.
use .log().block() instead of .subscribe(...). You lose the customization of what to do on each event, but log() will print those out for you (provided you have a logging framework configured). block() will revert to blocking mode and do pretty much what I suggested with the CountDownLatch above. It returns the value once available or throws an Exception in case of error.
instead of log() you can customize logging or other side effects using .doOnXXX(...) methods (there's one for pretty much every type of event + combinations of events, eg. doOnSubscribe, doOnNext...)
If you're doing a unit test, use StepVerifier from the reactor-tests project. It will subscribe to the flux/mono and wait for events when you call .verify(). See the reference guide chapter on testing (and the rest of the reference guide in general).
Issue is that in created anonymous class onSubscribe method does nothing.
If you look at implementation of LambdaSubscriber, it requests some number of events.
Also it's easier to extend BaseSubscriber as it has some predefined logic.
So your subscriber implementation would be:
MyServiceService service = new MyServiceService();
service.save("id")
.map(myUserMono -> new MyUser(myUserMono.getName().toUpperCase(), myUserMono.getId().toUpperCase()))
.subscribe(new BaseSubscriber<MyUser>() {
#Override
protected void hookOnSubscribe(Subscription subscription) {
System.out.println("Subscribed!" + Thread.currentThread().getName());
request(1); // or requestUnbounded();
}
#Override
protected void hookOnNext(MyUser myUser) {
System.out.println("OnNext on thread " + Thread.currentThread().getName());
// request(1); // if wasn't called requestUnbounded() 2
}
#Override
protected void hookOnComplete() {
System.out.println("onCompleted!" + Thread.currentThread().getName());
}
#Override
protected void hookOnError(Throwable throwable) {
System.out.println("onError!" + Thread.currentThread().getName());
}
});
Maybe it's not the best implementation, I'm new to reactor too.
Simon's answer has pretty good explanation about testing asynchronous code.

LWUIT ConnectionRequest: Bad Request on Blackberry

My lwuit application is working fine on Blackberry Simulator while on device the application installs successfully, starts normally, but where am having issues is on network connection. Trying to access network I get 400 Bad Request message. I don't no what am doing wrong, my network connection code is as below:
public ConnectionRequest prepareConnection(String page, String progressMsg, final int request)
{
final ConnectionRequest conR = new ConnectionRequest()
{
public void readResponse(InputStream input) throws IOException {
StringBuffer sb = new StringBuffer();
int ch;
while((ch=input.read()) != -1)
sb.append((char)ch);
httpResponse(sb.toString().trim(), request);
}
};
conR.setUrl(NetworkHandler.getURL()+page);
conR.setDuplicateSupported(true);
Progress progress = new Progress(progressMsg, conR)
{
public void actionCommand(Command command)
{
if(command.getCommandName().equals("Cancel"))
conR.kill();
}
};
conR.setDisposeOnCompletion(progress);
return conR;
}
private void login(String code)
{
Container container = Display.getInstance().getCurrent();
if(!validateLogin(container))
{
showDialogMessage("Alert", "Please enter your user name and password!");
return;
}
NetworkManager.getInstance().start();
ConnectionRequest conR = prepareConnection(NetworkHandler.LOGIN_PAGE, "Authenticating...", RequestType.LOGIN);
Dialog dialog = conR.getDisposeOnCompletion();
conR.setPost(true);
conR.addArgument("u", getFieldValue(findTxtUserName(container)));
conR.addArgument("p", getFieldValue(findTxtPassword(container)));
conR.addArgument("c", code);
NetworkManager.getInstance().addToQueue(conR);
dialog.show();
}
public void onLoginForm_BtnLoginAction(Component c, ActionEvent event) {
login("");
}
Please I want you guys to help me out.
Thanks in Advance.
The login me
This usually indicates a problem in APN configuration on the device. Normally Blackberry app's workaround incorrect APN configurations automatically which is a pretty difficult thing to do. CodenameOne does that seamlessly but LWUIT does not.

Resources