Pages

Wednesday, June 22, 2016

Firebase Analytics integrate in Android


Hello, Today writing post for how to integrate Firebase Analytics in Android Application. Firebase Analytics is a free to analytic for android application.

1. Download firebase SDK  (Google Play services SDK from the Android SDK Manager)
2. Create a project in the Firebase Consol and download json file
3. Android studio 1.5 or latter and Android 2.3 or newer.
4. Check firebase report.


1. Firebase SDK : First update your Google Play services from the Android SDK Manager.

Check in Extras

Google Play Services installed rev 30 or up
Google Repository installed rev 26  or up. both are required to updated.


2. Create Project in Firebase Consol

* Select Add Firebase to your android App



 *  Add Package name here and click ADD APP button. Here make sure to add that package name to use in application.

* Download google-services.json File and click continue




*Here you can see to how to init Firebase sdk in android application. Click Finish


3. Create Application in Android studio and integrate Firebase SDK

 In Android studio select New > New Project
* Add Application and package name (package name is same as added Firebase project)


 * Select here Android minimum sdk version


* Select Empty Activity


* Enter Activity Name


* Now Copy google-services.json file and past to project's module folder "app/" folder





*  Add rules to your root-level build.gradle file, to include the google-services plugin:


* Add dependency for Firebase Analytics to your app-level build.gardle file and add plugin bottom
after add dependency and plugin then click Sync Now Button





*Create App.java and create FirebaseAnalytics object in Application class


 
package com.limbani.firebaseanalyticsdemo;

import android.app.Application;

import com.google.firebase.analytics.FirebaseAnalytics;


public class App extends Application {

    private static FirebaseAnalytics mFirebaseAnalytics;
    @Override
    public void onCreate() {
        super.onCreate();
        this.mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    }

    public static FirebaseAnalytics getFirebaseAnalytics() {
        return mFirebaseAnalytics;
    }
}

* MainActivity.java clas and add Firebase LogEven see in code. You can add more Event log see in FirebaseAnalytics.Event


package com.limbani.firebaseanalyticsdemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {

    private Button btn_click;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_click = (Button) findViewById(R.id.btn_click);

        btn_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Here Add Firebase LogEvent
                Bundle bundle = new Bundle();
                bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "btn_click");
                bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Next Activity");
                bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Button");
                App.getFirebaseAnalytics().logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

                startActivity(new Intent(MainActivity.this, SecondActivity.class));
            }
        });
    }
}


* activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.limbani.firebaseanalyticsdemo.MainActivity">

    <Button
        android:id="@+id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next Activity" />
</RelativeLayout<

* Create SeconActivity.java class and activity_second.xml file


package com.limbani.firebaseanalyticsdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
}

* activity_second.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.limbani.firebaseanalyticsdemo.SecondActivity">

</RelativeLayout>



* Edit AndroidMenifest.xml File


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.firebaseanalyticsdemo">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"></activity>
    </application>

</manifest>


4. Check Report in Firebase :



Error Resolve

1. If you find error while sync time like faild to resolve firebase then you need to check 1st point to Google Play Service updated or not.


2. Execution faild for task ':app:processDebugGoogleServices'.
> File google-services.json is missing. ......
getting this error then you are missing to add google-services.json or miss placed this file. check 3rd point

Download Source code

Thank you :)

Wednesday, May 25, 2016

How to check FingerPrint feature available in android?

In android API 23 added Finger Print feature for lock or unlock your phone, authorize purchases, or sign in to apps.
So how to check fingerprint feature available or not in android device? check below.

Method 1 :
  if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
      Toast.makeText(this, "Finger print not supported", Toast.LENGTH_SHORT).show();
  }

Method 2 :
 
   FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
   if (!fingerprintManager.isHardwareDetected()) {
       // Device doesn't support fingerprint authentication
       Toast.makeText(this, "Device doesn't support fingerprint authentication", Toast.LENGTH_SHORT).show();
   } else if (!fingerprintManager.hasEnrolledFingerprints()) {
       // User hasn't enrolled any fingerprints to authenticate with
      Toast.makeText(this, "User hasn't enrolled any fingerprints to authenticate with", Toast.LENGTH_SHORT).show();
   } else {
      // Everything is ready for fingerprint authentication
      Toast.makeText(this, "Everything is ready for fingerprint authentication", Toast.LENGTH_SHORT).show();
   }

This method required USE_FINGERPRINT permision. Add in Menifest file.
    
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
Thank you :)

Saturday, June 13, 2015

How to format datetime to RelativeTime from now in android


Hello everyone,

Today I am write post for display Relative Time from now in application.
Some application we need to show Datetime in relative to now. Application like chat, post Artical and showing news headline.


Relative time from now mean, examples below:

10 second ago
1 min ago
5 hours ago
2 days ago


I find out some way to format Datetime to Relative time from now.

1. Using DateUtils API
2. Using android-ago library


1. Using DateUtils API 

First understand below methods and it's parameters

Method 1 : 


public static CharSequence getRelativeTimeSpanString (long time, long now, long minResolution)

Returns a string describing 'time' as a time relative to 'now'.
Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "in 42 minutes".

Parameters:

time : the time to describe, in milliseconds
now : the current time in milliseconds
minResolution : the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS

See below Example code and Output one by one.
If you have Date-time is a string then first convert in Date Object see in code.


Exmaple  :


try {
 long now = System.currentTimeMillis();
 String datetime1 = "06/12/2015 03:58 PM";
 SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
 Date convertedDate = dateFormat.parse(datetime1);
  
 CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
  convertedDate.getTime(),
        now,
        DateUtils.SECOND_IN_MILLIS);
   
 txt_time.append(relavetime1+"\n\n");
 System.out.println(relavetime1);
} catch (ParseException e) {
 e.printStackTrace();
}

If current Time is a "06/12/2015 03:58:10 PM" then output like below because we pass minResolutions parameters is SECOND_IN_MILLIS.


 Output : 
 10 second ago


See below case after change minResolutions parameters


Case 1. MINUTE_IN_MILLIS then output : "0 minutes ago"
Case 2. HOUR_IN_MILLIS then output : "0 hours ago"
Case 3. DAY_IN_MILLIS then output : "Today"
Case 4. WEEK_IN_MILLIS then output : "12 Jun 2015"


Method 2:


public static CharSequence getRelativeTimeSpanString (long time, long now, long minResolution, int flags)

Returns a string describing 'time' as a time relative to 'now'.
Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "in 42 minutes".
Can use FORMAT_ABBREV_RELATIVE flag to use abbreviated relative times, like "42 mins ago".

Parameters:

time the time to describe, in milliseconds
now : the current time in milliseconds
minResolution : the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
flags a bit mask of formatting options, such as FORMAT_NUMERIC_DATE or FORMAT_ABBREV_RELATIVE


Example code  1 :


try {
 long now = System.currentTimeMillis();
 String datetime1 = "06/12/2015 03:58 PM";
 SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
 Date convertedDate = dateFormat.parse(datetime1);
  
 CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
  convertedDate.getTime(),
        now,
        DateUtils.SECOND_IN_MILLIS,
        DateUtils.FORMAT_ABBREV_RELATIVE);
   
 txt_time.append(relavetime1+"\n\n");
 System.out.println(relavetime1);
} catch (ParseException e) {
 e.printStackTrace();
}

If current Time is a "06/12/2015 03:58:10 PM" then output like below because we pass minResolutions parameters is SECOND_IN_MILLIS.


 Output : 
 10 secs ago


See below case if change minResolutions parameters


Case 1. MINUTE_IN_MILLIS then output : "0 mins ago"
Case 2. HOUR_IN_MILLIS then output : "0 hours ago"
Case 3. DAY_IN_MILLIS then output : "Today"
Case 4. WEEK_IN_MILLIS then output : "12 June"


Example code 2 :
If target datetime is "06/12/2015 06:00 PM" and current time is "06/12/2015 05:15 PM" output shows like below



Case 1. SECOND_IN_MILLIS then output : "in 45 mins" 
Case 2. MINUTE_IN_MILLIS then output : "in 45 mins"
Case 3. HOUR_IN_MILLIS then output : "in 0 hours"
Case 4. DAY_IN_MILLIS then output : "Today"
Case 5. WEEK_IN_MILLIS then output : "12 June"

2. Use Library - Android Ago

We can use this library for relative time from now.
It contain custom TextView class and auto refresh Relative time.

Just add custom TextView on your xml layout and like below.


<com.github.curioustechizen.ago.RelativeTimeTextView
    android:id="@+id/timestamp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_primary" />


Add below code in your activity


RelativeTimeTextView tvTimestamp = (RelativeTimeTextView) convertView.findViewById(R.id.timestamp);
tvTimestamp.setReferenceTime(<here pass timestamp>);


that's it.
More information about Library See Here
Thank you :)


Thursday, April 23, 2015

Android BluetoothAdapter state change listner


In this post I have write code for BuletoothAdapter state change listener. When we use Bluetooth in application then we can check bluetooth is On or Off. But on run time we can use BroadcardReceiver.

Register a BroadcastReceiver to listen for any state changes of the BluetoothAdapter.


Add below code in Activity Class.

Create BroadcastReciver instance variable in your activity (also you can create separate class file)


private final BroadcastReceiver mbluetoothStateReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();

   if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
    switch (state) {
    case BluetoothAdapter.STATE_OFF:
     Toast.makeText(getApplicationContext(), "Bluetooth off", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_OFF:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth off...", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_ON:
     Toast.makeText(getApplicationContext(), "Bluetooth on", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_ON:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth on...", Toast.LENGTH_SHORT).show();
     break;
    }
   }
  }
 };


and Then add code to Register and Unregister BroadcastReceiver as follows


@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_bluetoothlistner);
 
  // Register broadcasts receiver for bluetooth state change
  IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiver(mbluetoothStateReceiver, filter);
 }
 
 @Override
 public void onDestroy() {
  super.onDestroy();
  // Unregister broadcast listeners
  unregisterReceiver(mbluetoothStateReceiver);
 }


Full code of the Activity

public class BluetoothStateListenerActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_bluetoothlistner);

  // Register broadcasts receiver for bluetooth state change
  IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiver(mbluetoothStateReceiver, filter);
 }

 private final BroadcastReceiver mbluetoothStateReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();

   if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
    switch (state) {
    case BluetoothAdapter.STATE_OFF:
     Toast.makeText(getApplicationContext(), "Bluetooth off", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_OFF:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth off...", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_ON:
     Toast.makeText(getApplicationContext(), "Bluetooth on", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_ON:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth on...", Toast.LENGTH_SHORT).show();
     break;
    }
   }
  }
 };

 @Override
 public void onDestroy() {
  super.onDestroy();
  // Unregister broadcast listeners
  unregisterReceiver(mbluetoothStateReceiver);
 }
}


Add below permission on AndroidManifest.xml file

<uses-permission android:name="android.permission.BLUETOOTH" />

Thank you :)