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

Monday, 12 August 2019

FCM Client App and the Server Sample which sends token to FCM which will PUSH to the Client


Following Dependencies in Gradle



implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.firebase:firebase-analytics:16.3.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'com.google.firebase:firebase-core:16.0.9'

Following service class

public class MyFirebaseInstanceIdService extends FirebaseMessagingService {





    @Override    
       public void onNewToken(String token) {
        super.onNewToken(token);
        Log.e("Refreshed token:",token);


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences.edit().putString("fcmToken",token).apply();
    }


    @Override    
       public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

       //if the message contains data payload        
       //It is a map of custom keyvalues        //we can read it easily        
        if(remoteMessage.getData().size() > 0){
            //handle the data message here    }

        //getting the title and the body        
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();

        //then here we can use the title and body to build a notification    
    }
}

Manifest Add the following



<service    android:name=".service.MyFirebaseInstanceIdService"android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

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


Run the App you should be able to see token in logcat


We can then send this token to the webservice using HttpURLConnection to the server


public class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {


        try{

            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
             
            //For Emulator testing we can use this IP if we are running our server in 8080
            URL url = new URL("http://10.0.2.2:8080/register/token");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         //   conn.setReadTimeout(15000 /* milliseconds */);           // conn.setConnectTimeout(15000 /* milliseconds */);            
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty( "charset", "utf-8");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches (false);
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("content" ,  sp.getString("fcmToken"," "));            
            Log.e("params",postDataParams.toString());
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(postDataParams.toString());


            writer.flush();
            writer.close();
            os.close();
            conn.connect();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(
                        new InputStreamReader(
                                conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override    
     protected void onPostExecute(String result) {

        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }
    }


    

Call this in onCreate() or on Button Click



App Server has now the token it will send this to FCM which will PUSH Notification to the Client App




public class ServerDemo {

 //This is the server key which we will get from Firebase console our App and the FCM Tab we should select
 public final static String AUTH_KEY_FCM = "key=AAMMM";
 public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 
      //This is the token which client App receives from FCM
 public static String CLIENT_TOKEN = null;

 public static void main(String[] args) throws IOException {

  FileOutputStream fileOutputStream = null;
  BufferedReader bufferedReader = null;

  try { 
 //Here we are fetching the token which we received from FCM
   URL url = new URL("http://localhost:8080/register/alltoken");

   bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
   fileOutputStream = new FileOutputStream("C:\\Softwares\\Test.txt");
   String input;

   while ((input = bufferedReader.readLine()) != null) {
    CLIENT_TOKEN = input;
    System.out.println(input);
    fileOutputStream.write(input.getBytes());
   }

   bufferedReader.close();
   fileOutputStream.close();
   // System.out.println(results.get(0));

  } catch (MalformedURLException me) {
   me.printStackTrace();
  } catch (IOException ie) {
   ie.printStackTrace();
  }

  sendPOST();
 }

 private static void sendPOST() throws IOException {
  System.out.println("Inside post "+CLIENT_TOKEN);
  URL obj = new URL(API_URL_FCM);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  con.setRequestMethod("POST");
  // con.setRequestProperty("User-Agent", USER_AGENT);

  // For POST only - START
  con.setDoOutput(true);

  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type", "application/json");

  con.setRequestProperty("Authorization", AUTH_KEY_FCM);

  String postJsonData = "{\r\n" + 
    "  \"notification\": \r\n" + 
    "  {\r\n" + 
    "    \"title\": \"Hello Client This is From Server\",\r\n" + 
    "    \"text\": \"Your Text\",\r\n" + 
    "    \"sound\": \"default\",\r\n" + 
    "    \"badge\": \"1\",\r\n" + 
    "    \r\n" + 
    "    \"color\": \"#990000\",\r\n" + 
    "      \r\n" + 
    "    \r\n" + 
    "  },\r\n" + 
    "  \"priority\" : \"high\",\r\n" + 
    "  \"registration_ids\" : \r\n" + 
    "   [\r\n" + "\""+ 
          CLIENT_TOKEN+ "\""+ "\r\n" + 
    "    ]\r\n" + 
    "}";

  

  OutputStream os = con.getOutputStream();
  os.write(postJsonData.getBytes());
  os.flush();
  os.close();
  // For POST only - END
  con.connect();
  int responseCode = con.getResponseCode();
  System.out.println("POST Response Code :: " + responseCode);

  if (responseCode == HttpURLConnection.HTTP_OK) { // success
   BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
   String inputLine;
   StringBuffer response = new StringBuffer();

   while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
   }
   in.close();

   // print result
   System.out.println(response.toString());
  } else {
   System.out.println("POST request not worked");
  }
 }
}




Sunday, 30 June 2019

Disable few dates in Android using Android Date picker

final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);


c.add(Calendar.DATE, 3);
DatePickerDialog datePickerDialog = new DatePickerDialog(view.getContext(),
        new DatePickerDialog.OnDateSetListener() {

            @Override            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {

                txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

            }
        }, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());

c.add(Calendar.DATE, -6);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
datePickerDialog.show();

Tuesday, 5 February 2019

Android Latest Updates

In Google I/O 2018, a new publishing format has been introduced for Android applications called Android App Bundle. It is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play. Traditionally, Android apps are distributed using a special file called an Android Package(.apk).

Why should we use this new format?

  • Dynamic Delivery : Google Play’s new app serving model, called Dynamic Delivery, uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. For example, you don’t need other languages strings if you have set English as your default language.
  • No need to manually manage multiple APKs : You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads. For example, now you don’t have to create multiple APKs for devices with different screen resolutions.
  • Dynamic Feature Module : These modules contain features and assets that you can decide not to include when users first download and install your app. Using the Play Core Library, your app can later request to download those modules as dynamic feature APKs. For example, video calling feature and camera filters can be downloaded later on demand.
  • Reduced APK size : Using Split APK mechanism(explained later), Google Play can break up a large app into smaller, discrete packages that are installed on a user’s device as required. On average, apps published with app bundles are 20% smaller in size.
 
 

Monday, 7 January 2019

Android Location Services Using GPS BackGround Service to Update

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private ArrayList<String> permissionsToRequest;
    private ArrayList<String> permissionsRejected = new ArrayList();
    private ArrayList<String> permissions = new ArrayList();

    private final static int ALL_PERMISSIONS_RESULT = 101;
    LocationTrack gpsTracker;
    List<Address> addresses;
    Geocoder geocoder;

    private TextView displayTv,displayAddress;
    private static final String TAG = MainActivity.class.getSimpleName();
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        displayTv = (TextView)findViewById(R.id.tvDisplay);
        displayAddress = (TextView)findViewById(R.id.tvAddress);
        try {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        gpsTracker = new LocationTrack(MainActivity.this);
        if(gpsTracker.canGetLocation()){
            double latitude = gpsTracker.getLatitude();
            double longitude = gpsTracker.getLongitude();
            displayTv.setText(String.valueOf(latitude)+"   "+String.valueOf(longitude));

        }else{
            gpsTracker.showSettingsAlert();
        }



        LocalBroadcastManager.getInstance(this).registerReceiver(
                new BroadcastReceiver() {
                    @Override                    public void onReceive(Context context, Intent intent) {
                        String latitude = intent.getStringExtra(LocationTrack.EXTRA_LATITUDE);
                        String longitude = intent.getStringExtra(LocationTrack.EXTRA_LONGITUDE);

                        if (latitude != null && longitude != null) {
                            displayAddress.setText("Service started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);

                        }
                    }
                }, new IntentFilter(LocationTrack.ACTION_LOCATION_BROADCAST)
        );
    }








}
 
 
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

import static android.content.ContentValues.TAG;


/** * Created by namratha.asher on 12/21/2018. */
public class LocationTrack extends Service implements LocationListener {
    private final Context mContext;
    // flag for GPS status    boolean isGPSEnabled = false;
    // flag for network status    boolean isNetworkEnabled = false;
    // flag for GPS status    boolean canGetLocation = false;
    Location location; // location    double latitude; // latitude    double longitude; // longitude    // The minimum distance to change Updates in meters    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters    // The minimum time between updates in milliseconds    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute    // Declaring a Location Manager    protected LocationManager locationManager;
    public static final String ACTION_LOCATION_BROADCAST = LocationTrack.class.getName() + "LocationBroadcast";
    public static final String EXTRA_LATITUDE = "extra_latitude";
    public static final String EXTRA_LONGITUDE = "extra_longitude";
    public LocationTrack(Context context) {
        this.mContext = context;
        getLocation();
    }
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            // getting GPS status            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          //  isGPSEnabled = false;            // getting network status           /* isNetworkEnabled = locationManager                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);*/            isNetworkEnabled = false;
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled            } else {
                this.canGetLocation = true;
                // First get location from Network Provider                if (isNetworkEnabled) {
                    //check the network permission                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions((MainActivity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
                    }
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                       /* location = locationManager                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);*/                        List<String> providers = locationManager.getProviders(true);
                        Location bestLocation = null;

                        for (String provider : providers) {
                            Location l = locationManager.getLastKnownLocation(provider);
                            if (l == null) {
                                continue;
                            }
                            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                                // Found best last known location: %s", l);                                bestLocation = l;
                            }
                        }

                        if (bestLocation != null) {
                            latitude = bestLocation.getLatitude();
                            longitude = bestLocation.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        //check the network permission                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((MainActivity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
                        }
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }
    /**     * Stop using GPS listener     * Calling this function will stop using GPS in your app     * */    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(LocationTrack.this);
        }
    }
    /**     * Function to get latitude     * */    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
        // return latitude        return latitude;
    }
    /**     * Function to get longitude     * */    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
        // return longitude        return longitude;
    }
    /**     * Function to check GPS/wifi enabled     * @return boolean     * */    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    /**     * Function to show settings alert dialog     * On pressing Settings button will lauch Settings Options     * */    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing Settings button        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
    @Override    public void onLocationChanged(Location location) {
        Log.v("TEST****", "IN ON LOCATION CHANGE, lat=" + latitude + ", lon=" + longitude);
//        Toast.makeText(this,"Loc",Toast.LENGTH_LONG).show();        if (location != null) {
            Log.d(TAG, "== location != null");

            //Send result to activities            sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        }
    }

    private void sendMessageToUI(String lat, String lng) {

        Log.d(TAG, "Sending info...");

        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra(EXTRA_LATITUDE, lat);
        intent.putExtra(EXTRA_LONGITUDE, lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    @Override    public void onProviderDisabled(String provider) {
    }
    @Override    public void onProviderEnabled(String provider) {
    }
    @Override    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override    public IBinder onBind(Intent arg0) {
        return null;
    }
}
 
Layout
 
<?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:id="@+id/activity_main"    android:layout_width="match_parent"    tools:context=".MainActivity"    android:layout_height="match_parent">

    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/btn"        android:layout_centerInParent="true"        android:text="GET LOCATION" />

    <TextView        android:id="@+id/tvDisplay"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/btn"        android:layout_centerHorizontal="true"        android:layout_marginTop="39dp"        android:text="TextView" />

    <TextView        android:id="@+id/tvAddress"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_alignStart="@+id/btn"        android:layout_marginStart="15dp"        android:layout_marginTop="75dp"        android:text="TextView" />
</RelativeLayout>

Tuesday, 27 February 2018

Activity LifeCycle

➤onCreate() — Called when the activity is first created
 ➤onStart() — Called when the activity becomes visible to the user
 ➤onResume() — Called when the activity starts interacting with the user
➤onPause() — Called when the current activity is being paused and the previous activity is being resumed
➤onStop() — Called when the activity is no longer visible to the user
➤onDestroy() — Called before the activity is destroyed by the system (either manually or by the system to conserve memory)
➤onRestart() — Called when the activity has been stopped and is restarting again

onclick of home btn which method called?
onpause onSaveInstanceState and onstop and then onresume
Restart the app after pressing home
onRestart
onStart
onResume


on backpressed?
onPause
onStop
onDestroy
onSaveInstanceState was not called, because there is no current state to resume – when you re-enter you will be back at the beginning
Restart the app after pressing back
onCreate
onStart
onResume

Turn off with the power button
onSaveInstanceState
onPause
 
When the phone was suspended, onSaveInstanceState and onPause were called in different orders, and onStop was called in some cases.
Turn on with the power button
onResume

from one activity to other-
when onrestart is called?
go from act1 to act 2 and when you come back from act2 to act1 on restart-- onstart--on resume is called

 

Friday, 16 February 2018

Android how to Clear App Data Programatically

public class MainActivity extends AppCompatActivity {

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

//clearApplicationData();  ---Method 1
/* ((ActivityManager)MainActivity.this.getSystemService(ACTIVITY_SERVICE)) .clearApplicationUserData();*/ --- Method 2 // deleteAppData(); ---- Method 3
}

private void deleteAppData() {
try {
// clearing app data String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);

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


public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}


public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}

return deletedAll;
}

}

Wednesday, 14 February 2018

Espresso Check for the Youtube URL



//Using Espresso Intent to check whether the appropriate URL is openedIntents.init();
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData("req_url"));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(startsWith("Video"))).perform(click());
intended(expectedIntent);
Intents.release();

Add this dependency in build.gradle
androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'

Start and Send data to Activity from ADB

1)Navigate to platform-tools which is inside sdk android
2)Then type adb shell am start -n yourpackagename/.activityname
3)Starts the Activity
4)To send the data
adb shell am start -n yourpackagename/.activityname -e myKey test
5)You can retrieve from App Side
getIntent().getStringExtra("myKey")
6)Done

Friday, 2 February 2018

Nexus not detecting in android studio

1.Update Android SDK (Google USB Driver)

2.From PC Control Panel, System -> Device manager -> Right click Nexus 4 -> Update driver.

3.Set android-sdk-folder\extras\google\usb_driver as path to search, include subfolders checked.

If windows tells you that the driver is up to date, just uninstall the driver (right click on nexu4 -> uninstall driver) and start from step 2 again.
After that, open a cmd and type adb kill-server and then a adb devices, now it will include your device.


More details
https://stackoverflow.com/questions/20343014/adb-doesnt-show-nexus-5-device

Git in Android Studio

How to get all changes of release branch to developer branch?


1)Navigate to VCS-->Git--->Merge Changes
There make sure you are on your current branch
2)Branvhes to merge:select the appropriate branch which you want to incorporate
3)Commit
4)Push

Sunday, 28 January 2018

SSL Pinning OverView


Certificate Pinning:

To summarize, pinning a certificate means that your app is verifying that the site the app is communicating with is the actual site by comparing the certificate presented by the site to one bundled in the app. This prevents a man-in-the-middle attack on your app.

SSL pinning isn’t something you want to implement in all your applications, but it makes sense when developing high-risk apps that need strong protection

HOW DOES THIS WORK ON ANDROID ?

  • obtain a certificate for the desired host (preferably the whole certificate chain)
  • make sure the certificate is in .bks format - this step is crucial in order for pinning to work properly across all devices
  • use Apache HTTP client shipped with Android - initialize it to use the obtained .bks keystore for SSL connections

Risks Involved

There is a downside to pinning a certificate. If the site rotates its certificate on a regular basis, then your application would need to be updated regularly. For example, Google rotates its certificates, so you will need to update your application about once a month (if it depended on Google services).

Example of a Failure Scenario
1. App has pinned certificate(s) to some domain name.
2. Certificates get updated on the server side.
3. Version of the app that pinned to old certificate(s) and doesn't know about new certificate(s) won't allow connection
.


Links





Challenges






https://dev.to/drankolq/certificate-pinning-your-android-and-ios-apps

Wednesday, 10 January 2018

Room Persistence Library

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
The library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.

Components of RoomWe have 3 components they are
Entity : It’s nothing but a model class annotated with @Entity where all the variable will becomes column name for the table and name of the model class becomes name of the table.Database: This is an abstract class where you define all the entities that means all the tables that you want to create for that database.Dao: This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here.

Sample Example is shown below

Following dependencies in build.gradle file

 // ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.0.0"    
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
// Room    
implementation "android.arch.persistence.room:runtime:1.0.0"    
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
// Paging    
implementation "android.arch.paging:runtime:1.0.0-alpha4-1"
// Test helpers for LiveData    
testImplementation "android.arch.core:core-testing:1.0.0"
// Test helpers for Room    
testImplementation "android.arch.persistence.room:testing:1.0.0"

Java Classes

@Entity(tableName = "user")
public class User {

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;


}


@Dao
public interface  UserDao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user where first_name LIKE  :firstName AND last_name LIKE :lastName")
    User findByName(String firstName, String lastName);

    @Query("SELECT COUNT(*) from user")
    int countUsers();

    @Insert    
    void insertAll(User... users);

    @Delete    
    void delete(User user);
}


@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {


    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database")
                            // allow queries on the main thread.                            // Don't do this on a real app! See PersistenceBasicSample for an example.                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }

}


public class MainActivity extends AppCompatActivity {

    List<User> usersList;

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

        //Storing sample Data       // populateWithTestData(AppDatabase.getAppDatabase(MainActivity.this));        //Retrieving the data for specific user        User testUser = findUser(AppDatabase.getAppDatabase(MainActivity.this), "Abhi", "Sai");
        Toast.makeText(MainActivity.this, String.valueOf(testUser.getUid()), Toast.LENGTH_LONG).show();
        //Retrieving all users data        usersList = getUsersList(AppDatabase.getAppDatabase(MainActivity.this));
        for (User testUserItems : usersList) {
            Log.i("User ", testUserItems.getFirstName() + "  " + testUserItems.getLastName());
        }

    }

    private static void populateWithTestData(AppDatabase db) {
        User user = new User();
        user.setFirstName("Sanjay");
        user.setLastName("Shah");
        addUser(db, user);
        user.setFirstName("Abhi");
        user.setLastName("Sai");
        addUser(db, user);

    }


    private static User addUser(final AppDatabase db, User user) {
        db.userDao().insertAll(user);
        return user;
    }


    private static User findUser(final AppDatabase db, String fName, String lName) {
        User tUser;
        tUser = db.userDao().findByName(fName, lName);


        return tUser;
    }

    private static List<User> getUsersList(final AppDatabase db) {

        List<User> userList;
        userList = db.userDao().getAll();


        return userList;
    }
}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...