Posts

Showing posts from 2016

Android: launch android email with email id

Intent intent = new Intent ( Intent . ACTION_SENDTO , Uri. parse ( "mailto:" + mEmail .getText().toString())); intent.putExtra( Intent . EXTRA_EMAIL , mEmail .getText().toString()); startActivity( Intent . createChooser (intent, "Send Email" ));

Android: launch android dialer with mobile number

Intent intent = new Intent ( Intent . ACTION_DIAL , Uri. parse ( "tel:" + mContactNo .getText().toString())); startActivity(intent);

Android View Collapse and Expand Animations

// To animate view slide out public void collapseView(View view) { HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), 0 ); heightAnim.setDuration( 500 ); view.startAnimation(heightAnim); } // To animate view slide in public void expandView(View view) { HeightAnimation heightAnim = new HeightAnimation(view, 0 , ( int ) ( 51 * AppDisplayManager. getInstance ().getDeviceDensity())); heightAnim.setDuration( 200 ); view.startAnimation(heightAnim); } public class HeightAnimation extends Animation { protected final int originalHeight ; protected final View view ; protected float perValue ; public HeightAnimation(View view, int fromHeight, int toHeight) { this . view = view; this . originalHeight = fromHeight; this . perValue = (toHeight - fromHeight); } @Override protected void applyTransformation( float interpolatedTime, Transformation t) { view .getLayoutParams(). hei

Working with Android Hierarchy Viewer

Working with Hierarchy Viewer #Hierarchy Viewer allows you to debug and optimize your user interface. #It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display. # Connect your mobile device to your computer. # Open your application in Android Studio, build the source, and run it on your device. (debug application only) # From Android Studio, start the Android Device Monitor: Tools > Android > Android Device Monitor. # Allow USB Debugging on your phone (if asked). # Make sure your device and the package for your application are showing in the Devices (DDMS mode) or Windows (Hierarchy Viewer mode) tab. You can choose Window > Reset Perspective to get back to the default arrangement. # In Android Device Monitor (ADM), in the menu bar, choose Window > Open Perspective, and in the popup click Hierarchy View. The left dot represents the Draw Process of the rendering pipeline. - Measure Th

Android: Create Android application video from command line

adb shell screenrecord --size 1280x720 /sdcard/example.mp4

Android: On Configuration change or Orientation change

savedInstanceState will be null when the activity is created. savedInstanceState will be not null when the activity is re created check condition on the activity onCreate. if ( null == savedInstanceState) { // Add fragment to the activity }

React-Native: Android React Native Setup

# Install Adnroid SDK # Install Node Js # Install react # run the following commands npm install -g react-native-cli react-native init AwesomeProject # To run with local server, run the following commands under your react-native project root directory react-native start  /dev/null 2>&1 & adb reverse tcp:8081 tcp:8081

Android Error: Found com.google.android.gms:play-services:8.4.0, but version 8.3.0 is needed for the google-services plugin

Make sure that the following line is  at the end of the app build.gradle  file: apply plugin : 'com.google.gms.google-services'

Android: *.jks file view

use the following command to view the jks file, which will ask for password. keytool -v -list -keystore *.jks 

Android: Gradle Tasks

following commands can be used for build, run and test on device.. Echo Clean Project call gradle clean Echo Build Project call gradle assembleRelease Echo Install APK and Run Android Tests call gradle connectedAndroidTest

Android: Events from JavaScript to Android

//Add interface to webview webView.addJavascriptInterface( new WebAppInterface(getApplicationContext()), "Android" ); class WebAppInterface { Context mContext ; /** * Instantiate the interface and set the context */   WebAppInterface(Context c) { mContext = c; } /** * Show a toast from the web page */   @JavascriptInterface   public void showToast(String toast) { Toast. makeText ( mContext , toast, Toast. LENGTH_SHORT ).show(); } //Create a toast / event in JavaScript <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); } </script>

Android Build Error: UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0"

Change the build tool version buildToolsVersion "24.0.0 rc2" to buildToolsVersion " 23.0.2 "

Android: ProGuard source code

Enable ProGuard in Android gradle build, make sure that the build variant is same. minifyEnabled true Add following snippet to App ' proguard-rules.pro' file -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontskipnonpubliclibraryclassmembers -dontpreverify -dontnote -ignorewarnings -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* # not to proguard dependent library packages -keep class com.squareup.** -keep class com.android.volley.** # not to proguard android components -keep public class * extends android.app.Activity -keep public class * extends android.app.Fragment -keep public class * extends android.support.v4.app.Fragment -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -dontwarn ** -dontnote ** # to generate the mapping.txt file -printmapping mapping.txt

Android: de compile an android apk file

extract apk file as zip or rar file convert the dex file to jar using dex2jar tool then open the jar file with jd_gui tool.

Android: Display Manager

public class AppDisplayManager { private static AppDisplayManager ourInstance = new AppDisplayManager(); private Display mDisplay ; public static AppDisplayManager getInstance() { return ourInstance ; } private AppDisplayManager() { WindowManager wm = (WindowManager) CommonUtil. getAppContext ().getSystemService(Context. WINDOW_SERVICE ); mDisplay = wm.getDefaultDisplay(); } public int getDeviceWidth() { if ( null != mDisplay ) { if (android.os.Build.VERSION. SDK_INT >=  android.os.Build.VERSION_CODES. HONEYCOMB_MR2 ) { Point point = new Point(); mDisplay .getSize(point); return point. x ; } else { return mDisplay .getWidth(); } } else { return 0 ; } } public int getDeviceHeight() { if ( null != mDisplay ) { if (android.o

Android: Dynamic column/grid for ListView

public class DynamicColumnGridManager extends GridLayoutManager {     private int minItemWidth;     public DynamicColumnGridManager(Context context, int minItemWidth) {         super(context, 1);         this.minItemWidth = minItemWidth;     }     @Override     public void onLayoutChildren(RecyclerView.Recycler recycler,                                  RecyclerView.State state) {         updateSpanCount();         super.onLayoutChildren(recycler, state);     }     private void updateSpanCount() {         int spanCount = getWidth() / minItemWidth;         if (spanCount < 1) {             spanCount = 1;         }         this.setSpanCount(spanCount);     } } mLayoutManager = new DynamicColumnGridManager(getApplicationContext(), mItemWidth); mRecyclerView.setLayoutManager(mLayoutManager);

Android: animate/translate RecyclerView items using ItemTouchHelper

ItemTouchHelper.Callback callback = new ItemMoveHelper(ItemTouchHelper. UP |  ItemTouchHelper. DOWN , ItemTouchHelper. START | ItemTouchHelper. END ); ItemTouchHelper helper = new ItemTouchHelper(callback); helper.attachToRecyclerView(m RecyclerView ); ItemTouchHelper moves the items' of a recyclerView to translateX/Y properties to  reposition them class ItemMoveHelper extends ItemTouchHelper.SimpleCallback { public ItemMoveHelper( int dragDirs, int swipeDirs) { super (dragDirs, swipeDirs); } @Override public boolean onMove(RecyclerView recyclerView,  RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { Collections. swap ( mBagList , viewHolder.getAdapterPosition(), target.getAdapterPosition()); mAdapter .notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition()); return false ; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int

Android: Change the ActionBar primary and secondary colors

    <!-- Base application theme. -->     <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">         <item name="colorPrimary">@color/appPrimaryColor</item>         <item name="colorPrimaryDark">@color/appSecondaryColor</item>     </style>

Android: ListView Pagination

While having pagination do not re create the adapter object, instead update the existing adapter object. so that the list view will not be refreshed or re created. It will be updated with new items.

Android: Animate Navigation icon with DrawerArrowToggle style

<style name="AppTheme" parent="Theme.AppCompat.Light">     <item name="drawerArrowStyle">@style/DrawerArrowStyle</item> </style> <!-- change the spinBars for diff animation  --> <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">     <item name="spinBars">true</item>     <item name="color">@android:color/white</item> </style>

Android: SSL/https POST request using Volley

RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext(), new HurlStack(null, getSSL())); final JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { if (null != jsonObject) { try { String accessToken = (String) jsonObject.get("access_token"); AppPreference.getInstance().setPreference(AppKeys.ACCESS_TOKE                                                          N, accessToken); haveAccessToken = true; mHandler.sendEmptyMessage(1); Log.i(getClass().getSimpleName(), accessToken); } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(getActivity().getApplicationContext(), "Login Success",                                                    Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Overri

Android: Standalone login with SQLiteOpenHelper

import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /**  * Created by Chandra on 31-10-2015.  */ public class LoginSQLiteHelper extends SQLiteOpenHelper {     public static final String TABLE_NAME = "table_login";     public static final String COLUMN_ID = "_id";     public static final String COLUMN_USER_EMAIL = "user_email";     public static final String COLUMN_USER_PWD = "user_pwd";     public static final String COLUMN_USER_NAME = "user_name";     public static final String COLUMN_USER_NO = "user_no";     private static final String DATABASE_NAME = "login.db";     private static final int DATABASE_VERSION = 1;     // Database creation sql statement     private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "             + TABLE_NAME + "(" + COLUMN_ID + " IN

Android: WebView back navigation

webview = (WebView) rootView.findViewById(R.id. testWebView ); webview .setWebViewClient( new MyBrowser()); private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true ; } }  

Android: Check Mobile/Device network state

boolean isWiFi = false ; boolean isMobile = false ; boolean isBluetooth = false ; ConnectivityManager cm = (ConnectivityManager) CommonUtil. getAppContext ().getSystemService(Context. CONNECTIVITY_SERVICE ); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if ( null != activeNetwork) { boolean isConnected = activeNetwork.isConnectedOrConnecting(); if (isConnected) { if (activeNetwork.getType() == ConnectivityManager. TYPE_WIFI ) { isWiFi = activeNetwork.getType() == ConnectivityManager. TYPE_WIFI ; } else if (activeNetwork.getType() == ConnectivityManager. TYPE_MOBILE ) { isMobile = activeNetwork.getType() == ConnectivityManager. TYPE_MOBILE ; } else if (activeNetwork.getType() == ConnectivityManager. TYPE_BLUETOOTH ) { isBluetooth = activeNetwork.getType() == ConnectivityManager. TYPE_BLUETOOTH ; } return (isWiFi || isMobile || isBluetooth); } } return false ;

Android: Ping an external server from android device

// ping external servers public static final String PING_ONE = "ping -c 1 your server IP" ; public static final String PING_TWO = "ping -c 1 your server IP " ; try { Process p1 = java.lang.Runtime. getRuntime ().exec( PING_ONE ); int p1RetExitVal = p1.waitFor(); if (p1RetExitVal == 0 ) { // Internet available   networkState = true ; } else { Process p2 = java.lang.Runtime. getRuntime ().exec( PING_TWO ); int p2RetExitVal = p2.waitFor(); if (p2RetExitVal == 0 ) { // Internet available   networkState = true ; } } } catch (Exception e) { networkState = false ; e.printStackTrace(); }

Android: Layer Drawable uasage with Picasso Librarry

// create drawable array with index drawableArray [index] = new BitmapDrawable(getResources(),  Picasso. with (AppUtils. getAppContext ()) .load( componentUri ) .get()); //images will be drawn based on the index order. higher index will be drawn on top. LayerDrawable layerDrawable = new LayerDrawable( drawableArray ); image .setImageDrawable(layerDrawable);