Friday, January 13, 2017

Secure your android java codes from decompile or reverse engineering

One Idea, If you implement JAVA 8 library with your android projects, then it is impossible to decompile by any tools available. I will show you how you implement that.

There is 2 types of gradle files:
1. Project's gradle.build and
2. App's gradle.build

For point. 1 you make changes like:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        // ADD THIS
        classpath 'me.tatarka:gradle-retrolambda:3.2.5'        
}

Then For point 2, there are some additions are required like:

apply plugin: 'com.android.application'
// ADD THIS
apply plugin: 'me.tatarka.retrolambda'

android {
// ADD THIS
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8    }
}

Yupp, thats all. My friend. Your codes are secured from any type of reverse engineering.

Note: Plus point is you can use LAMBDA with your logic now. And addition with
compile 'com.annimon:stream:1.0.9'
You can use JAVA STREAM as well.. ;)

Tuesday, January 10, 2017

Set timer with interval at starting on boot, Show notification on proper event/condition

First of all, we create Class that starts at Boot

public class OnBootReceiver extends BroadcastReceiver {

 @Override public void onReceive(Context context, Intent intent) {

  AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  Intent intent = new Intent(context, OnBootCalling.class);
  PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.HOUR_OF_DAY, Constant.alarmHour);
  calendar.set(Calendar.MINUTE, Constant.alarmMinute);

  alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
   Constant.alarmInterval, alarmIntent);

 }

and add this to your androidManifest.xml

<receiver    android:name=".OnBootReceiver"    android:enabled="true">
    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />

        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        <action android:name="android.intent.action.REBOOT" />
    </intent-filter>
</receiver>

So, everytime, On specific time, as set in Alarm, will call OnBootCalling.class

public class OnBootCalling extends WakefulBroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {

  if (conditionIsSatisfied)
   ComponentName comp = new ComponentName(context.getPackageName(),
    AlarmService.class.getName());
  startWakefulService(context, (intent.setComponent(comp)));
  setResultCode(Activity.RESULT_OK);
  break;
 }
}
}
}
}

which will call AlarmService.class, which will call notification

public class AlarmService extends IntentService {

 public AlarmService() {
  super("AlarmService");
 }

 @Override
 public void onHandleIntent(Intent intent) {

  //If you want to play default sound with notification 
  Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  Ringtone ringtone = RingtoneManager.getRingtone(PlayerApp.getContext(), alarmUri);
  ringtone.play();

  Intent intent = new Intent(PlayerApp.getContext(), MainActivity.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, 0);

  Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(PlayerApp.getContext())
   .setSmallIcon(R.drawable.ic_music)
   .setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_music))
   .setContentTitle("Alert")
   .setTicker("Ticking Alert")
   .setStyle(new NotificationCompat.BigTextStyle().bigText("For BigView, Your Message comes here"))
   .setContentText("Your Message comes here")
   .setAutoCancel(true)
   .setSound(defaultSoundUri)
   .setContentIntent(pendingIntent);
  //                .addAction (R.drawable.ic_menu_manage,
  //                        getString(R.string.anyaction), pendingIntent);

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

  notificationManager.notify(401, notificationBuilder.build());
 }
}

Note: Make sure you get proper context

Do not forget to add these lines to your Manifest

<receiver android:name=".OnBootCalling" />

<service android:name=".AlarmService" android:enabled="true" />

Also add these permissions

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

Hope, this helps you somewhere.

Tuesday, October 18, 2016

default clock packages including Marshmallow to open Alarm in android

String clockImpls[][] = {
        {"Sony Ericsson Xperia Z", "com.sonyericsson.organizer", "com.sonyericsson.organizer.Organizer_WorldClock"},
        {"ASUS Alarm Clock", "com.asus.alarmclock", "com.asus.alarmclock.AlarmClock"},
        {"ASUS Desk Clock", "com.asus.deskclock", "com.asus.deskclock.DeskClock"},
        {"Sony Alarm", "com.sonyericsson.alarm", "com.sonyericsson.alarm.Alarm"},
        {"Standard Alarm", "com.android.alarmclock", "com.android.alarmclock.AlarmClock"},
        {"Marshmallow Alarm", "com.android.deskclock", "com.android.deskclock.DeskClock"},
        {"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl"},
        {"Standard Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
        {"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
        {"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
        {"Samsung Galaxy S", "com.sec.android.app.clockpackage", "com.sec.android.app.clockpackage.ClockPackage"}};

Full Code for clock widget


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.widget.RemoteViews;

public class ClockWidget extends AppWidgetProvider {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        PendingIntent pendingIntent;
        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {

            RemoteViews views = new RemoteViews(context.getPackageName(),
                    R.layout.clock_widget);

            try {
                pendingIntent = PendingIntent.getActivity(context, 0, getAlarmPackage(context), 0);
                views.setOnClickPendingIntent(R.id.clock, pendingIntent);
            } catch (Exception e) {
                Log.e("pendingExceptions", e.getMessage() + " " + getAlarmPackage(context));
            }

            AppWidgetManager
                    .getInstance(context)
                    .updateAppWidget(
                            intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS),
                            views);
        }
    }

    public Intent getAlarmPackage(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);

        String clockImpls[][] = {
                {"Sony Ericsson Xperia Z", "com.sonyericsson.organizer", "com.sonyericsson.organizer.Organizer_WorldClock"},
                {"ASUS Alarm Clock", "com.asus.alarmclock", "com.asus.alarmclock.AlarmClock"},
                {"ASUS Desk Clock", "com.asus.deskclock", "com.asus.deskclock.DeskClock"},
                {"Sony Alarm", "com.sonyericsson.alarm", "com.sonyericsson.alarm.Alarm"},
                {"Standard Alarm", "com.android.alarmclock", "com.android.alarmclock.AlarmClock"},
                {"Marshmallow Alarm", "com.android.deskclock", "com.android.deskclock.DeskClock"},
                {"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl"},
                {"Standard Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
                {"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
                {"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
                {"Samsung Galaxy S", "com.sec.android.app.clockpackage", "com.sec.android.app.clockpackage.ClockPackage"}};

        boolean foundClockImpl = false;

        for (String[] clockImpl : clockImpls) {
            String packageName = clockImpl[1];
            String className = clockImpl[2];
            try {
                ComponentName cn = new ComponentName(packageName, className);
                packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
                AlarmClockIntent.setComponent(cn);
                foundClockImpl = true;
            } catch (NameNotFoundException ignored) {
            }
        }
        if (foundClockImpl) {
            return AlarmClockIntent;
        } else {
            return null;
        }
    }
}

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(...).