Thursday, 15 September 2016

Firebase Cloud Messaging FCM on Android device

Steps to integrate Firebase Cloud Messaging FCM with android.



1.open firebase.google.com
------------------------------------------------------
2.click on "go to console" which will be displayed on top right of the screen
------------------------------------------------------
3.now link will be directed to https://console.firebase.google.com/
------------------------------------------------------
4.click on create new project
------------------------------------------------------
5.now a pop up will come, asking to you to enter the project name and country. you can give any name. no restriction to the app name. enter the name of your country.
------------------------------------------------------
6.create project
------------------------------------------------------
7.click on firebase to your app(for android)
------------------------------------------------------
8.copy application id from(your android project which you want to integrate FCM) your app level gradle file and paste it to package name field in firebase. In the same package firebase(related) service classes should present.
------------------------------------------------------
9.copy debug key sha1 and paste it to debug key field in firebase.
Note: use this command to get sha1 key from windows
installed java path.....jdk/bin>keytool -list -v -keystore c:\users\systemname\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
note down sha1 key and paste it.
------------------------------------------------------
10.now click add app, now google-services.json file will be downloaded. paste this file in app directory.
------------------------------------------------------
11.open your project level grade file. add this - classpath 'com.google.gms:google-services:3.0.0' line in dependencies
------------------------------------------------------
12.open app level gradle file , paste this line - apply plugin: 'com.google.gms.google-services' at the bottom of the file.
------------------------------------------------------
13.add following lines in the app level gradle file.
compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
Note: always add updated dependencies.(https://firebase.google.com/docs/android/setup)
------------------------------------------------------
14.add FirebaseInstanceIDService.java file
Note: change ip address in the below file

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("token refresh =",token);
        registerToken(token);
    }
    private void registerToken(String token) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("http://your-ip-address/fcm/register.php")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
------------------------------------------------------
15.now add FirebaseMessagingService.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d("msg=",remoteMessage.getNotification().getBody());
        showNotification(remoteMessage.getData().get("message"),remoteMessage.getNotification().getTitle());
    }

    private void showNotification(String message,String title) {
        Log.d("wht is msg=",message);
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}
------------------------------------------------------
16.add the new two classes into android manifest file.(they are services , so service tags must be used to define them)
Note:this is how your manifest file look like this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fcm.calcify.com.fcmexampple">
    <application
        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>
        <service
            android:name=".FirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service
            android:name=".FirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

------------------------------------------------------

17.app level gradle file must look like this

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "fcm.calcify.com.fcmexampple"
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
apply plugin: 'com.google.gms.google-services'

------------------------------------------------------

18. project level gradle file

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
---------------------------------------------
19.run the android project. copy the token from the console. now it is very important to note that you get token only once(first run). if you didnt copy token file. uninstall app  clean and build it now note down token.
------------------------------------------------------
20.now open this link https://console.firebase.google.com/. if you are logged in, you will see your project created in firebase.
------------------------------------------------------
21.click on your project. now select notification from the list for left of the screen(scroll down if you cant see notification link).
------------------------------------------------------
22.now click on new message. enter message text and label. select delivery date as "send now".
------------------------------------------------------
23. select your app. now select target as single device.
------------------------------------------------------
24. after selecting single device , you will be asked to enter FCM registration token. here enter your token.
------------------------------------------------------

Wednesday, 7 September 2016

when to use try catch over throws key word in java

hello all
you should be careful while using throws keyword in method declaration. if you do so then the exception that may thrown from your method may go unnoticed. so it is good to use try catch for a piece of code and handle the exception.

class Example
{
   public void method()throws Exception
      {
   //the exception may come here , but we cant notice as we have declared method as throws        //exception.
     //so use try catch here.
      }
}

//or you can have another choice, use try catch where you call method

Example e = new Example();
try{
e.method
}
catch(Exception e)
{
 //handle here
}

Wednesday, 20 July 2016

how to enable location service in android marshmallow

You need to add a dependency to your app build.gradle:

compile 'com.google.android.gms:play-services:8.1.0'
then you can use following example by calling this method:
private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i(TAG, "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i(TAG, "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

reference link : https://github.com/googlesamples/android-play-location/blob/master/LocationSettings/app/src/main/java/com/google/android/gms/location/sample/locationsettings/MainActivity.java

Sunday, 29 May 2016

My View On Hinduism

Hindus must stop from trying to prove that Hinduism is a religion. It is not a religion it is the way of life or it is a culture.This culture may worship 33million gods, in some way they are our ancestors, we worship them not as god, we worship their ideal life, their contribution to humankind, their wisdom, their teachings, their struggles and sacrifices.we worship nature and animals because we know they are part of our civilization and we depend on each other. we worship tools because, they made our life easier. if we keep on trying to prove that Hinduism is a religion we may end up in
giving rise to extremists.

When you know that you do not belong to any particular religion you will feel liberated and your intelligence will never stop working.

Just think this culture has survived from thousands of years without single prophet, without single holy book and without conversion.
This is not a miracle this is the way of life.

This is only my opinion and i draw this opinion from teachings of swami Vivekananda and Sadhguru.

Tuesday, 26 April 2016

how to start mongodb server in windows

Steps to start mongodb server in windows
1. Open the command prompt
2. Open the directory where you have installed mongodb
3. Suppose you have installed mongodb in 'D' drive. open the directory upto bin folder
4. D:\>cd mongo\bin will take to bin directory.
5. Now run the mongo db server using command D:\mongo\bin>mongod --dbpath d:\mongo\data

 done, server will start. if not please check the command again and path where you installed  mongodb.

thankyou


Wednesday, 6 April 2016

AAPT err: ERROR: Unable to open PNG file Android

hello
sometimes you will get error like unable to open png files in android studio. it is because your project path is lengthy. it should kept as short as possible. this error will resolve after you path reduced to short.
thanku
mithun

Saturday, 2 April 2016

How to get SHA1 fingerprint for android

step 1: open command prompt
step 2:open the directory where you have installed jdk
C:\Program Files\Java\jdk1.8.0_60\bin
step 3: type command "keytool -list -v -keystore c:\users\UserName\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android"

the word in bold font UserName should be replaced by user name of computer or os.

sterp 4: press enter. there you go you will get SHA1 fingerprint for android