Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, 21 August 2017

Ionic 3 and Angular 4: Insert and Delete with Token Based Restful API

This is the continued series of article on developing a mobile app with Ionic and Angular JS. This post deals with updating and deleting any post on the application. This also explains how to show the loading image by making an Ajax call. While deleting a post, it will show an alert message to confirm whether to delete or not. This post is all about this. Hope you all make use of this series of articles on Ionic and Angular to build your own mobile app.

Ionic 3 and Angular 4: Insert and Delete with Token Based Restful API

Read more »
Share:

Monday, 14 August 2017

Some Updates to Apps Using Google Play services

Doug Stevenson
Doug Stevenson
Developer Advocate
There are a couple recent changes to the way you build your Android apps with Google Play services (and Firebase SDKs, which are distributed as part of Play services). Here's what you need to know to stay up to date.

1. Play services (and Firebase) dependencies are now available via maven.google.com

Until recently, developers were required to update their Android tools to make use of new versions of the local maven repository that contains Play services compile dependencies. Only after updating were the Android build tools able to locate them. Now, the dependencies are available directly from maven.google.com. You can update your app's Gradle build scripts to use this repository by simply configuring the build like this:

allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}

Note the new Google maven repository. This is where dependencies are now hosted. Using Gradle 4.0 and later, you can simply specify google() as a shortcut instead. Once configured like this, Gradle will be able to locate, download, and cache the correct Play services dependencies without requiring an update to the Android build tools. Play services SDKs going back to version 3.1.36 will be available in this repo.

You can read more about Google's maven repo here.

2. Starting with Play services dependencies version 11.2.0, your app's compileSdkVersion must be at least 26

When you upgrade your app's Play services dependencies to 11.2.0 or later, your app's build.gradle must also be updated to specify a compileSdkVersion of at least 26 (Android O). This will not change the way your app runs. You will not be required to update targetSdkVersion. If you do update compileSdkVersionto 26, you may receive an error in your build with the following message referring to the Android support library:

This support library should should not use a different version (25) than the compileSdkVersion (26).

This error can be resolved by upgrading your support library dependencies to at least version 26.0.0. Generally speaking, the compileSdkVersion of your app should always match the major version number of your Android support library dependencies. In this case, you'll need to make them both 26.

Share:

Tuesday, 8 August 2017

Ionic Split Pane with Login and Logout System.

I received a tutorial request from one of my blog readers to implement Ionic Split Pane with the login system. Ionic has been improving and releasing new desktop layout features. This post is an enhancement to my previous application. SplitPane is the new component introduced in Ionic 2.2.0. This targets to create apps of any screen size like desktops and tablets. With this, it is easy to show a side menu with side-by-side navigation controllers. Let’s see how we do this, and follow the demo below for more details.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.

Read more »
Share:

Friday, 4 August 2017

Firebase Performance Monitoring for Android Tip #1: Automatic Traces for All Activities

Doug Stevenson
Doug Stevenson
Developer Advocate

If you haven't tried Firebase Performance Monitoring yet, many Firebase developers have found it to be a helpful way to get a sense of some of the performance characteristics of their iOS or Android app, without writing many extra lines of code. To get more detailed information beyond what's collected automatically, you'll eventually have to write some custom traces and counters. Traces are a report of performance data within a distinct period of time in your app, and counters let you measure performance-related events during a trace. In today's perf tip, I'll propose a way to add potentially many more traces to your Android app without writing very much code at all.

Android apps are typically made up of a collection of activities that present some task or data to the user. For the purpose of hunting down potential performance problems, it can be handy to define a trace for every Activity in your app, so you can study the results later in the Firebase console. If your app has lots of activities, it might be kind of a pain to write the code for all of them. Instead, you can write a little bit of code that instruments all of them with their own trace.

Android gives you a way to listen in on the lifecycle of every single Activity in your app. The listeners are implementations of the interface ActivityLifecycleCallbacks, and you can register one with the Application.registerLifecycleCallbacks()method. For measuring performance, I suggest creating a trace that corresponds to the onStart() and onStop() lifecycle methods. When an activity is "started", that means it's visible on screen, and when it's "stopped", it's no longer visible, so I think this is a good place to define a trace that tracks an activity while it's actually doing things. Here's the start of an implementation of ActivityLifecycleCallbacks that keeps track of traces for each of your activities. First we'll make it a singleton so it can be easily accessed everywhere (or you might want to use some form of dependency injection):

public class PerfLifecycleCallbacks
implements Application.ActivityLifecycleCallbacks {

private static final PerfLifecycleCallbacks instance =
new PerfLifecycleCallbacks();

private PerfLifecycleCallbacks() {}
public static PerfLifecycleCallbacks getInstance() {
return instance;
}
}

Then, inside that class, I'll add some members that manage custom traces for each Activity:

    private final HashMap<Activity, Trace> traces = new HashMap<>();

@Override
public void onActivityStarted(Activity activity) {
String name = activity.getClass().getSimpleName();
Trace trace = FirebasePerformance.startTrace(name);
traces.put(activity, trace);
}

@Override
public void onActivityStopped(Activity activity) {
Trace trace = traces.remove(activity);
trace.stop();
}


// ...empty implementations of other lifecycle methods...

This will start a trace when any activity is started, and stop the same trace when the activity is stopped. For the name of the trace, I'm using the simple class name of the activity object, which is just the class name without the full java package. (Note: if you do this, make sure that your Activity class names are unique, if they're spread across Java packages!)

I'll add one more method to it that will return the trace of a given Activity object. That can be used in any activity to get a hold of the current trace so that counters can be added to it:

    @Nullable
public Trace getTrace(Activity activity) {
return traces.get(activity);
}

This class should be registered before any Activity starts. A ContentProvider is a good place to do that. If you're not familiar with how that works, you can read about how Firebase uses a ContentProvider to initialize.

public class PerfInitContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
context = getContext();
if (context != null) {
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(
PerfLifecycleCallbacks.getInstance());
}
}
}

Don't forget to add the ContentProvider to your app's manifest! This will ensure that it gets created before any Activity in your app.

Once this ContentProvider is in place, your app will automatically create traces for all your activities. If you want to add counters to one of them, simply use the getTrace() method from the PerfLifecycleCallbacks singleton using the current Activity object. For example:

private Trace trace;

@Override
protected void onCreate(Bundle savedInstanceState) {
trace = PerfLifecycleCallbacks.getInstance().getTrace(this);
// use the trace to tally counters...
}

Be sure to think carefully about the counters you want to log! You'll want to measure things that will give you information that helps inform a decision about how the user experience could be improved in your app. For example, you could record the ratio of cache hits to misses to help tune the amount of memory for the cache. And be sure to follow Firebase on Twitter to get more Firebase Performance Monitoring tips.

Share:

Thursday, 27 July 2017

Find More Bugs Using StrictMode with Firebase Test Lab for Android

Doug Stevenson
Doug Stevenson
Developer Advocate

Sometimes the worst bugs to track down are the ones that seem to be impossible to reproduce. Or worse, inconsistent performance problems that can cause "Application Not Responding" errors in Android apps. No matter how much test code you write, these types of errors seem to have a way of sneaking into your app and causing problems for your users. However, with some clever use of Android's StrictModeAPI, alongside Firebase Test Lab for Android, you can find out about these problems before they reach production!

Over the years since Android was first available, a number of best practices have been observed for writing solid apps. For example, you shouldn't be performing blocking I/O on the main thread, and you shouldn't store references to Activity objects that are held after the Activity is destroyed. While it's likely that no one will force you to observe these practices (and you may never see a problem during development), enabling StrictMode in your app will let you know where you've made a mistake. These are called "policy violations", and you configure these policies with code in your app.

Personally, I don't want any of my code to cause any StrictMode violations. In fact, I'd like to consider them bugs that are just as serious as a regular crash, because they could crash my app in some cases! And, in fact, I can configure all StrictMode violations to crash the app. The Java code for that looks like this:

    
private static final StrictMode.ThreadPolicy FATAL_THREAD_POLICY =
new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build();

private static final StrictMode.VmPolicy FATAL_VM_POLICY =
new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build();

public static void enableFatalStrictMode() {
if (shouldEnableFatalStrictMode()) {
StrictMode.setThreadPolicy(FATAL_THREAD_POLICY);
StrictMode.setVmPolicy(FATAL_VM_POLICY);
}
}

Here I have both a ThreadPolicy(for the main thread) and a VmPolicy(for the entire app) that look for all known violations, and will both log that violation and crash the app. Take a look through the javadoc for those builders to learn about all the situations they can catch.

Also notice that I'm enabling the policies conditionally. You probably don't want an accidental violation to crash on your users in production, so the method shouldEnableFatalStrictMode() typically looks like this, which activates it for your debug builds only:

    
private static boolean shouldEnableFatalStrictMode() {
return BuildConfig.DEBUG;
}

What I'd like to do is take this further and have StrictMode crash my app also when it's running in Firebase Test Lab. This is handy because the crash will fail the test, and I'll get a report about that in the test results. For that to happen, I can change the method to query a system setting on the device that's unique to devices in Test Lab. Note that this requires an Android Context to obtain a ContentResolver:

    
private static boolean shouldEnableFatalStrictMode() {
ContentResolver resolver = context.getContentResolver();
String isInTestLab = Settings.System.getString(resolver, "firebase.test.lab");
return BuildConfig.DEBUG || "true".equals(isInTestLab);
}

Now, my instrumented tests (and the automated Robo test) will crash with any StrictMode violations, and I'll see those very clearly in my Test Lab report. Here's an app that crashed in Test Lab with a StrictMode violation during a Robo test:

This doesn't tell you exactly what happened, though. Digging into the logs in the test report, I see the details of the violation right before the crash:


D/StrictMode(6996): StrictMode policy violation; ~duration=80 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=327743 violation=2
D/StrictMode(6996): at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1415)
D/StrictMode(6996): at java.io.UnixFileSystem.checkAccess(UnixFileSystem.java:251)
D/StrictMode(6996): at java.io.File.exists(File.java:807)
D/StrictMode(6996): at android.app.ContextImpl.getDataDir(ContextImpl.java:2167)
D/StrictMode(6996): at android.app.ContextImpl.getPreferencesDir(ContextImpl.java:498)
D/StrictMode(6996): at android.app.ContextImpl.getSharedPreferencesPath(ContextImpl.java:692)
D/StrictMode(6996): at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:360)
D/StrictMode(6996): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:167)
D/StrictMode(6996): at com.google.firebasesandbox.MainActivity.onCreate(MainActivity.java:25)
D/StrictMode(6996): at android.app.Activity.performCreate(Activity.java:6982)
D/StrictMode(6996): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
D/StrictMode(6996): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
D/StrictMode(6996): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
D/StrictMode(6996): at android.app.ActivityThread.-wrap11(Unknown Source:0)
D/StrictMode(6996): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
D/StrictMode(6996): at android.os.Handler.dispatchMessage(Handler.java:105)
D/StrictMode(6996): at android.os.Looper.loop(Looper.java:164)
D/StrictMode(6996): at android.app.ActivityThread.main(ActivityThread.java:6541)
D/StrictMode(6996): at java.lang.reflect.Method.invoke(Native Method)
D/StrictMode(6996): at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
D/StrictMode(6996): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

So we've discovered here that an activity's onCreate() called getSharedPreferences(), and this method ends up reading the device filesystem. Blocking the main thread like this could be the source of some jank in the app, so it's worth figuring out a good way to move that I/O to another thread.

Now we have a way to check for StrictMode violations during a test, but there's still a few more details to work out.

When should I enable StrictMode?

If you do this immediately when the app launches (in an Application subclass or a ContentProvider), there is a subtle bug in some versions of Android that may need to be worked around in order to avoid losing your StrictMode policies when the first Activity appears.

When should I disable StrictMode?

There might be some times when you know there is a violation, but you can't fix the code right away for whatever reason (for example, it's in a library you don't control). In that case, you might want to temporarily suspend the crashing behavior and simply log it instead. To temporarily suspend the crash, you can define a couple other non-fatal policies and swap them in where you know there's an issue to ignore:

    
private static final StrictMode.ThreadPolicy NONFATAL_THREAD_POLICY =
new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();

private static final StrictMode.VmPolicy NONFATAL_VM_POLICY =
new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build();

public static void disableStrictModeFatality() {
StrictMode.setThreadPolicy(NONFATAL_THREAD_POLICY);
StrictMode.setVmPolicy(NONFATAL_VM_POLICY);
}

Similarly, you may not want to track all the possible violations all the time. In that case, you might want to instruct the policy builder to only detect a subset of the potential issues.

Get out there and test your app!

While StrictMode violations are not always the worst thing for your users, I've always found it educational to enable StrictMode in order to find out where my app might be causing problems. In combination with Firebase Test lab, it's a great tool for maximizing the quality of your app.

Share:

Wednesday, 12 July 2017

Ionic 3 and Angular 4: JSON Parsing with Token Based Restful API

We have covered most of the topics in building a mobile application using Ionic 3 and Angular JS 4. Today’s topic is to pull in data for news feed from a server and display it on your website. This is suggestible post since it does proper verification at the backend based on token. All it does is, it will verify system token and user token at the backend and then pulls data using feed API url. I have also added an extra code to the previous post for login authentication with PHP Restful API for showing alert messages. Please do follow the below video and code for your understanding.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.

Read more »
Share:

Wednesday, 5 July 2017

Test Your Game with Firebase Test Lab for Android

Doug Stevenson
Doug Stevenson
Developer Advocate

Testing your application is a great way to help maximize its quality, and many of you know that Firebase Test Lab for Android has some useful tools for testing Android apps. If you're the type of engineer who likes to maximize test coverage by writing instrumented tests (and regular unit tests), you can send those to Test Lab for execution. Even if you don't like writing tests, you have some options. You can record instrumented tests by interacting with your app using Espresso Test Recorder in Android Studio. And there's almost no effort required at all to run a Robo test that automatically crawls your app.

These tests are helpful for data-driven apps because there are robust test frameworks that understand how to navigate the Android platform widgets used to receive input and display data on screen. However, most games don't work with platform widgets. Games typically take over the screen using their own UI elements, and provide their own touch controls. As a result, it's extremely difficult to write instrumented tests for testing games, and Robo test won't know how to navigate the game at all.

To help deal with these challenges with testing games, the Test Lab team has come up with a way for game developers to test their games effectively across many of the devices that Test Lab offers. It's a new type of test called a Game Loop Test, and it's available today in beta.

How does a Game Loop test work?

If you've seen arcade video games operate, you know that they're always showing something on screen, typically some automated demo of the game, called "attract mode". With Firebase Test Lab, game developers can now use this concept of attract mode to construct test scenarios, and Test Lab will arrange for those scenarios to be invoked in sequence. This gives developers the opportunity to test a wide variety of game levels and situations in a single test run on all the devices provided by Test Lab. If there are any problems with a scenario, you'll find out which ones are problematic, so you can focus your efforts on improving that specific case.

Even better, Test Lab now provides performance data with every report. Of particular interest to game developers is a graph of the rendered frame rate over time throughout the test, tied to a video of the device display. This helps you quickly identify the parts of your game that aren't rendering at an acceptable FPS.

In addition to FPS, there are other performance metrics available for all apps. You'll be able to see your app's CPU utilization, memory usage, and network ingress and egress. Notice how you can jump directly to the point in the video where you're observing performance problems.

If you're a game developer, now is a great time to check out Firebase Test Lab for Android to see what it can do to help the quality of your game.

Share:

Wednesday, 28 June 2017

Ionic 3 and Angular 4: Adding Custom Fonts like Open Sans and Font Awesome.

We all know that Ionic is the useful framework for building HTML 5 mobile applications. It is mainly designed for the front end. When it comes to look and feel of the Ionic website, you have to work more on your application branding standards. Ionic default icons are not up to current market standards. This tutorial is all about how to add custom downloaded fonts like open sans and font awesome for icons into the Ionic application. Let’s see how you use customized fonts in your Ionic website.

Ionic 3 and Angular 4:Create a Welcome Page with Login and Logout.

Read more »
Share:

Thursday, 22 June 2017

Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.

Here is the continued article on my previous post for creating a welcome page with login and logout. Today’s post explains how to implement login authentication system for your AngularJS applications. It will show you how to log in with a user and store the user session, so it deals with token based authentication. Since we are using token based authentication, it protects if any unauthorized request is made and notices for a new login if required. This makes your application’s authentication to be more secured compared with any other authentication system. Every user details will be stored in an external database and a PHP based API is used in the backend for handling this authentication. Hope you’ll find it more easily using this as your authentication system in your AngularJS projects. Let’s look into the live demo and follow the below code.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.

Read more »
Share:

Monday, 12 June 2017

Ionic 3 and Angular 4:Create a Welcome Page with Login and Logout.

Most of the mobile applications starts with welcome page with login and signup buttons. A proper login or signup redirects to application home page and there you can navigate to different pages and finally you can end up with a logout action. Today’s tutorial is all about this. Here I am using AngularJS 4 and Ionic 3. The combination of AngularJS and Ionic in handling login is a straight forward process. This design is already explained in my previous posts using ReactJS navigations. Lets see how to set a starting page using Ionic 3 and AngularJS4 and learn basic understanding of how the navigation works.

Ionic 3 and Angular 4:Create a Welcome Page with Login and Logout.

Read more »
Share:

Monday, 24 April 2017

React Native Router Navigations - Tutorial Part 3

This is again the continued post on React Native series. This post explains routing and navigation to different tabs in an application using React Native. Navigation is all about how the user can access possible sequences of pages in a web application. Routing is the encoding and decoding of URLs used in the application. Routing is supported by some set of rules. Each application must provide defined set of rules. Once the routing rules are defined, we can use the URLs containing view names and their parameters to navigate to different pages/tabs in the application.

React Native Router Navigations

Read more »
Share:

Wednesday, 19 April 2017

Ionic 3 and Angular 4: Working with Signature Pad.

This tutorial explains how to upgrade to Ionic 3 and Angular 4 and how to use signature pad for your application. If you are working with some agreement related project or something which needs some written proof from the customers, we might in need of a signature pad. The combination of Ionic 3 and Angular 4 provides some better features to achieve signature pad. This will allow you to sign/draw something on the application and save that image as data on the screen. Using this tutorial, you can also make a signature pad with Ionic 2 and Angular 3. Why late? Let’s start this small, but most commonly used task in your application.

Ionic 2 and Angular 2: Using the Native Camera

Read more »
Share:

Wednesday, 12 April 2017

Brand new course from Udacity and Google

Jen Person
Jen Person
Course Developer
What separates apps that are good ideas from apps that are really great? Analytics! Successful app developers rely on analytics to determine how users are really interacting with their app. Analytics are at the core of Firebase, helping you make actionable decisions to build products that people love.

We partnered with Udacity to offer a free 2-day interactive course that will help you learn how to use Firebase Analytics to grow your userbase on iOS and Android. Specifically, you'll see how to set goals and how to log users' interactions with an app. You'll even analyze real data from an app that's live in the Google Play Store and in the App Store! And you'll learn from people who live and breathe Firebase: experts Steve Ganem and Todd Kerpelman from Google, as well as Android and iOS developers from Google and Udacity.





The new course will include a combination of short videos, quizzes, code snippets, and a robust online community to help you learn. Check out the course on Android or iOS for free, and see all of our courses at udacity.com/google.
Share:

Thursday, 6 April 2017

Ionic 3 and Angular 2: Using the Native Camera, Take Multiple Photos with Delete Action.

Are you searching for easy camera access for taking multiple pictures in your mobile application? Then here is the post explaining on how to access camera and take pictures. In most recent days, this is achieved easily with the combination of Ionic framework and AngularJS. We have already discussed in my previous article, how easy it is to use pre-built it in components of Ionic with AngularJS and build awesome mobile apps. Today’s article explains Cordova plugin provided by Ionic framework to access camera , take picture and see the output. The most exciting thing about this article is, it explains you to upload multiple images you take in camera. Let’s follow the article and also the video tutorial on this.

Ionic 2 and Angular 2: Using the Native Camera

Read more »
Share:

Sunday, 2 April 2017

React Native JSON Parsing and Helper Functions - Tutorial Part 2

This is the continuation of previous article Getting started with React Native Template Design – Tutorial Part I. Today’s article and video tutorial explains how to parse and render the json data using some of the best React Native packages. It explains how to make ajax calls using fetch. Fetch is the networking API, which is chosen by React Native to get the JSON data and render it in the page. I hope embedded videos with blog posts are more advantageous for you to learn. I appreciate to take any feedback if you have, so that I can make it better.

React Native Template Design

Read more »
Share:

Wednesday, 29 March 2017

Using Firebase Cloud Messaging with Android O

Diego Giorgini
Diego Giorgini
Software Engineer


Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages to your apps and sites. It provides two types of messages:
  1. Notification Messages display a simple notification popup, with optional data payload.
  2. Data Messages deliver a JSON payload to your application and let your code handle it.
Data Messages are a great way to build custom notifications, when the layout provided by notification messages is not enough, or to trigger background operations like a database sync or the download of additional content (image attachments, emails, etc.)

How should Data Messages trigger background operations?

The best way to trigger a background operation from a data message is by using Firebase Job Dispatcher to take advantage of the Android JobScheduler and Google Play services API.

By using Firebase Job Dispatcher you allow the operating system to schedule your operation when it's best for the user (like avoiding extra work when the battery is very low, or when the CPU is already heavily used by other foreground applications). Firebase Job Dispatcher also guarantees that your background task will be performed, and not killed by the system when foreground applications require more resources.

Background Process Optimizations in Android O

To get started, check out the Android O Developer Preview site where you will find instructions on downloading and installing the required SDKs. For Firebase Development, you'll also need to install the Firebase SDKs for Android. Be sure to use version 10.2.1 or later for Android O development.

Android O introduces new background processes optimizations, which make the use of JobScheduler (or wrapper libraries like Firebase Job Dispatcher) a requirement for long-running background operations. Due to these optimizations, the FCM (hence GCM as well) callbacks onMessageReceived()and onTokenRefresh() have a guaranteed life cycle limited to 10 seconds (same as a Broadcast Receiver).

After the guaranteed period of 10 seconds, Android considers your process eligible for termination, even if your code is still executing inside the callback.

To avoid your process being terminated before your callback is completed, be sure to perform only quick operations (like updating a local database, or displaying a custom notification) inside the callback, and use JobScheduler to schedule longer background processes (like downloading additional images or syncing the database with a remote source).
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
FirebaseJobDispatcher dispatcher =
new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.mustSchedule(myJob);
}
/**
* Perform and immediate, but quick, processing of the message.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
We hope this helps you understand how to use FCM to schedule long-running background operations. This solution greatly helps Android to preserve battery life and ensures that your application works fine on Android O. In case you have any questions don't hesitate to ask us on our support channels.
Share:

Sunday, 26 March 2017

Getting Started with React Native Template Design - Tutorial Part 1

We always look for apps that are faster to develop and run, React Native is one such emerging framework. Being focused on mobile development; React Native is an open source framework from Facebook which can be run on multiple platforms and devices such as iOS and Android. React Native is a javascript library. You do not have to learn iOS’ Swift or Java for Android, all you need to know is Javascript. I am going to present series of articles on React Native. This article explains making of native mobile template using React Native. Today, I am introducing video tutorials on Youtube for an easy learning.

React Native Template Design

Read more »
Share:

Thursday, 9 February 2017

Complex Sign-in user flows made easy on Android with Firebase

Laurence Moroney
Laurence Moroney
Developer Advocate
Firebase Auth is a secure authentication system that allows users to sign in and sign up for your application. It also allows federated identity sign-in through providers like Facebook, Twitter and of course, Google.

Users expect a rich experience and the the open source FirebaseUI project makes all of this possible by solving complex identity management problems. Firebase UI uses a number of new tools and UX innovations to assist users through the sign-in and sign-up process. These enhancements come from years of research by the Google identity team in learning how to optimize sign-in conversion.
In this post, you'll see how to use the feature to do sign-in and sign-up in an Android app using both Google Sign-In and an email/password combination.
Getting Started
The best way to get started is to go to GitHub and use FirebaseUI!
You can find FirebaseUI for Android here.

After clicking the Download button, you'll get a zip file containing the code, as well as a sample app. We'll explore the sample app in this post to see how you can use FirebaseUI for yourself.

To access it, use Android Studio, and from the File->Open menu, navigate to the directory where you unzipped the code. You'll see an Android Studio project is available. It should look like this:



Before you can run it, you'll need a Firebase project in the Firebase console, which in turn will give you a google-services.json configuration file. To get this, follow these steps:

In Android Studio, click Tools->Firebase. The Firebase Assistant will open on the right hand side of the Android Studio window. You'll see an Authentication section, that you can select. It will have an action for 'Email and password authentication'



Click it, and you'll see some actions that you need to follow. The first of these is to 'Connect your app to Firebase'.



Click the button, and you'll see the 'Connect to Firebase' dialog.



You can select either an existing application, or create a new one as shown. Once you're done, press the 'Connect to Firebase' button.

Android Studio will create a Firebase application for you on the console. It may take a few moments. When it's done, you'll see status like this:



Next up, you'll need to add Firebase Authentication to your app. Note the text, and the link within it -- you have to go to the Firebase console, and from there you can set up the desired sign-in methods.



In the console, turn on the Email/Password and Google Sign-In providers. It should look like this:



Now click the 'Add Firebase Authentication to your app' button in the assistant, and you'll see the 'Add Authentication' dialog:



Select 'Accept Changes', and Android Studio will add the required libraries to your app. You're now ready to run it!
Running the FirebaseUI Auth App
You're now ready to run the app. On some versions of Android Studio, you might get an error telling you that Instant Run isn't working. If that's the case, you can disable it on the Android Studio->Preferences->Instant Run menu.

After running, you'll see this screen:



Select 'Auth UI demo', and you'll see this:



Be sure to leave 'Google' and 'Email' checked as shown. Try experimenting with them by clicking 'Start'. You will first see Android's hint selector, which automatically helps channel the user into either the sign-in or sign-up flow. In thisexample, on my device I have 2 Google IDs signed in on the device (and saved with Google Smart Lock), so when I click 'Sign In', I get a card showing both -- allowing me to bypass the sign-in screen. The hint selector will also include other accounts on the device as well as any other email addresses saved with Smart Lock for Passwords. If you aren't signed into Google or any other accounts on the device, you won't see this, and will get taken to the Sign-in Screen instead. After signing in, you have the option to add the account to Smart Lock, giving you this option.



And if I click 'None of the Above' -- I get my sign-in screen -- giving me the option to sign in with Google or sign in with Email.



Think of all the different user flows that you'd need to implement with this.
  1. If there's no Google Account, but you sign in with Google, you should have the option to create a new one, or use an existing one
  2. If there is only one Google Account, and you used it previously to sign in, then you can sign in right away with it.
  3. If there are multiple Google Accounts, you should be given the option to choose one, add an existing one, or create a new one.
Play with the app and you'll see all of these are implemented in a standard way. Once you've signed in, you'll see something like this -- where metadata about the signed-in user is available:



Remember that the same can apply for Email or other identity provider accounts. That's a lot of code you'd have to write. But let's take a look at the code for this app -- and you'll see just how much has been encapsulated for you in FirebaseUI Auth.
Exploring the Code
To explore the code, go back to Android Studio, and look in the App folder. In it, you'll see an 'auth' folder, and within that there are three activities.

The first of these, the AuthUiActivity renders the sign-in buttons, and handles the sign-in request and response. The LeakCatcher, as its name suggests, helps you detect memory leaks. Finally the SignedInActivity renders the details of your sign-in session -- which you saw above.



Let's take a look at the AuthUiActivity. In the onCreate method, you'll see this code:

 FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(SignedInActivity.createIntent(this, null));
finish();
}

This gets an instance of the abstract class FirebaseAuth, and if there's a current user -- i.e., if someone is already signed in, then go straight to the SignedInActivity.

While there may be multiple buttons (i.e. Sign In with Google, Sign In with Email etc), there's only one button control, called R.id.sign_in, and it handles the user interaction. So, in your code you should see this:

@OnClick(R.id.sign_in)
public void signIn(View view) {
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder()
.setTheme(getSelectedTheme())
.setLogo(getSelectedLogo())
.setProviders(getSelectedProviders())
.setTosUrl(getSelectedTosUrl())
.setIsSmartLockEnabled(mEnableSmartLock.isChecked())
.build(),
RC_SIGN_IN);
}


This creates a SignInIntent from the AuthUI class. The logic within handles all of the user flows mentioned earlier! AuthUI is fully open source, so you can inspect how it does it, but if you want to use it, this is all you need to do!

The intent will return an activity result when done, and if this is the result of the above, the request code will be RC_SIGN_IN, so we call the handleSignInResponse function, passing it the resultCode and the data that came back from the intent:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
handleSignInResponse(resultCode, data);
return;
}

showSnackbar(R.string.unknown_response);
}


This function queries the data that came back from the activity, and if it indicates a successful sign in, then it starts the SignedInActivity, passing it the response data, from where it will parse the user metadata:

  private void handleSignInResponse(int resultCode, Intent data) {
IdpResponse response = IdpResponse.fromResultIntent(data);

// Successfully signed in
if (resultCode == ResultCodes.OK) {
startActivity(SignedInActivity.createIntent(this, response));
finish();
return;
} else {
// handle failure conditions
}
}


The UI is also fully customizable, and you can see an example of this if you explore the styles.xml file in the project. This allows you to set the colors of the sign in activities provided. Here's an example of the 'dark' theme:

<style name="DarkTheme" parent="FirebaseUI">
<item name="colorPrimary">@color/material_gray_900</item>
<item name="colorPrimaryDark">@android:color/black</item>
…
</style>

Then, when creating the sign in intent, you can set the theme.

@OnClick(R.id.sign_in)
public void signIn(View view) {
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder()
.setTheme(R.style.DarkTheme)
.setLogo(getSelectedLogo())


Or, as you can see in the snippet above, you can also set the logo -- see the getSelectedLogo function for details. It's as easy as adding your logo to the resources and configuring that function to return it based on its resource id.

And that's all you need to do! All of the user flows are encapsulated in the AuthUI classes, giving you a high conversion UI for signing in and signing up, freeing you up to focus on your application logic! FirebaseUI is not just on Android. You can get the same easy to drop-in and customize high conversion UI for iOSand Javascript.

You can find the FirebaseUI Auth classes on GitHub at: https://github.com/firebase/FirebaseUI-Android-- check them out and get involved!
Share:

Thursday, 21 July 2016

PixelPhone Enhance your Experience Getting Over the Default UI of your Android Smartphone

PixelPhone is an app for your Android device that replaces your default phone app to offer you a better experience. It has features that you don't usually get through your pre-installed phone & contact apps. Since its initiation some years back, the app has constantly refined and improved its features to better suit user's needs. Once you start using the app, you would not want to go back to the previous default version of your phone.

PixelPhone Enhance your Experience Getting

Read more »
Share:

Wednesday, 8 October 2014

New Way to Download Free Apps - MoboMarket 3.0 Now Released

Today, android based smartphones are much more preferred over the Windows or iOS based phones. And one of the major aspects for this preference is the large number of amazing applications available in the Google Play Store which is the default marketplace for all the devices. However, today a very few people know that there are many other marketplaces other than the Play Store that offer you all the more amazing applications and games.


New Way to Download Free Apps - MoboMarket  3.0 Now Released
Read more »
Share: