Saturday, August 27, 2016

Confirm Exit OnBackpressed click back twice.

@Overridepublic void onBackPressed() {
    confirmExit(MainActivity.this);
}

import android.support.v4.app.ActivityCompat;

public static boolean doubleBackToExitPressedOnce = false;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void confirmExit(AppCompatActivity context) {
    if (doubleBackToExitPressedOnce) {
        ActivityCompat.finishAffinity(context);
    }

    doubleBackToExitPressedOnce = true;
    Toast.makeText(context, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}

Wednesday, August 24, 2016

Having gradle build issue with unknown reason?

Go to terminal
Type

gradlew build

and Enter.. Wait.. it will work..

Firebase Messaging Service Example Android

Add gradle dependency,

dependencies {
    compile 'com.google.firebase:firebase-messaging:9.0.0'}

Create MyFirebaseInstanceIDService.java and MyFirebaseMessagingService.java


import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        sendRegistrationToServer(refreshedToken);
    }
  
    private void sendRegistrationToServer(String token) {
        // here implement method that sends token to store somewhere to reuse.    }
}

and

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**     * Called when message is received.     *     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO(developer): Handle FCM messages here.        // If the application is in the foreground handle both data and notification messages here.        // Also if you intend on generating your own notifications as a result of a received FCM        // message, here is where that should be initiated. See sendNotification method below.        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Add these to AndroidManifest.xml, 

<service    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
<service    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

That's it. Very Simple. Here is sample that is getting through RemoteMessage.

Log.d(TAG, "remoteMessage" + remoteMessage.getData());
Log.d(TAG, "APS: " + remoteMessage.getData().get("aps"));

private String id, title, msg, type, image, sound;
try { if (remoteMessage.getData() != null) { id = remoteMessage.getData().get("id"); title = remoteMessage.getData().get("title"); msg = remoteMessage.getData().get("msg"); type = remoteMessage.getData().get("type"); image = remoteMessage.getData().get("image"); sound = remoteMessage.getData().get("sound");

        sendNotification();
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Retrofit 2 demo example

First of all, add gradle dependency

dependencies {
compile 'com.squareup.retrofit2:retrofit:2.1.0'    
compile 'com.squareup.retrofit2:converter-gson:2.0.0'    
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'}


Check for updated version.

Make one class that handle retrofit stuff

NetCall.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

/** * Created by axay on 09-05-2016. */

public class NetCall {
    String baseUrl = "http://example.com/service/";
    public Request request;

    public Call<JsonObject> featuredPlaylist(JsonObject jsonObject) {
        return request.featuredPlaylist(jsonObject);
    }

    public Call<JsonObject> allUserPlaylist(JsonObject jsonObject) {
        return request.allUserPlaylist(jsonObject);
    }

    public interface Request{
        @POST("library/featuredplaylist.php")
        Call<JsonObject> featuredPlaylist(@Body JsonObject jsonObject);

        @POST("library/alluserplaylist.php")
        Call<JsonObject> allUserPlaylist(@Body JsonObject jsonObject);

    }


    public NetCall(){
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        request = retrofit.create(Request.class);
    }
}

Now call this wherever you want.

Suppose In MainActivity.java

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

import com.google.gson.JsonObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

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

        JsonObject jsonObject = new JsonObject();

        new NetCall().featuredPlaylist(jsonObject).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject jsonObject1 = response.body();
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });

        new NetCall().allUserPlaylist(jsonObject).enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                JsonObject jsonObject1 = response.body();
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }
}
Now Parse JsonObject as per your requirements got in onResponse(...).