Tuesday, 4 August 2015

Chat Head like Facebook messenger android

You have seen in many application have the feature of rounded chat icon on the screen which will be always on screen above all applications as shown in the screen shots . The app that provide this feature is Facebook messenger app where there is a chat icon on the screen .

                                 


Step1) Add Permission in manifest file 

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

Step2) Make a class that extends the service 

public class ServiceChatHead extends Service {

  private WindowManager windowManager;
  private ImageView chatImage;

  @Override public IBinder onBind(Intent intent) {
    // Not used
    return null;
  }

  @Override public void onCreate() {
    super.onCreate();

    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    chatImage = new ImageView(this);
    chatImage.setImageResource(R.drawable.android_head);

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_PHONE,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;
  chatImage.setOnTouchListener(new View.OnTouchListener() {
  private int initialX;
  private int initialY;
  private float initialTouchX;
  private float initialTouchY;

  @Override public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        initialX = params.x;
        initialY = params.y;
        initialTouchX = event.getRawX();
        initialTouchY = event.getRawY();
        return true;
      case MotionEvent.ACTION_UP:
        return true;
      case MotionEvent.ACTION_MOVE:
        params.x = initialX + (int) (event.getRawX() - initialTouchX);
        params.y = initialY + (int) (event.getRawY() - initialTouchY);
        windowManager.updateViewLayout(chatHead, params);
        return true;
    }
    return false;
  }
});
    windowManager.addView(chatImage, params);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (chatImage != null) windowManager.removeView(chatImage);
  }
}


Step 3) Declare service in manifest file 

<service   android:name=".ServiceChatHead"></service>

Step4) Start the service that will display the icon and icon can be dragable to any position on screen

startService(new Intent(context, ServiceChatHead.class));



Enjoy Coding and share your knowledge 

Saturday, 20 June 2015

Android Swipe Down to Refresh ListView

SwipeRefreshLayout


You had seen in most of android apps like Gmail, Twitter  have an option to swipe / pull down to refresh it’s content. Whenever user swipes down from top, a loader will be shown and will disappear once the new content is loaded.

How it works

  • The ListView is placed as a child view to SwipeRefreshLayout.
  • This allows user the ability to show the loading spinner when user swipes the ListView edge. All the functionality of displaying loading bar is encapsulated inside SwipeRefreshLayout class.
  • When user swipes down, the OnRefreshListener events gets fired. You can handle this event to write the logic for downloading or refreshing data.
  • Note that, once data is downloaded, user has to manually call setRefreshing(false) to hide the refresh spinner.
Step 1) activity_main.xml

<android.support.v4.widget.SwipeRefreshLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"> 
 
 <!-- ListView is placed as a child view to SwipeRefreshLayout-->
 
     <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
     </ListView> 
 
 </android.support.v4.widget.SwipeRefreshLayout>

Step 2) MainActivity

public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener{

private SwipeRefreshLayout mSwipeRefreshLayout;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
      // Configure the swipe refresh layout
        mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById 
                                (R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
     // change the color scheme 
        mSwipeRefreshLayout.setColorScheme(
                R.color.swipe_color_1, R.color.swipe_color_2,
                R.color.swipe_color_3, R.color.swipe_color_4);
 
 
        } 

// listener when swipe event occurs
     @Override
    public void onRefresh() {
        // Start showing the refresh animation
        mSwipeRefreshLayout.setRefreshing(true);

        //calling update listview method 
        updateListView();
          
    }
 
      private void updateListView() {

        // write the logic here to update listview
             new AsyncTask<Void, Void, Void>() {

   @Override
   protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
   }
   @Override
   protected Void doInBackground(Void... params) {
    //Write your long running process 
    return null;
   }
   
   @Override
   protected void onPostExecute(Void result) {
 
                         // Signify that we are done refreshing
                          mSwipeRefreshLayout.setRefreshing(false);
  
                        super.onPostExecute(result);

   }
  }.execute();

        
    } 

}










Friday, 15 May 2015

Android detecting all supported Gestures

Android provides the GestureDetector class for detecting common gestures. Some of the gestures it supports include onDown(), onLongPress(), onFling(), and so on.

 

public class MainActivity extends Activity implements
        GestureDetector.OnGestureListener,
        GestureDetector.OnDoubleTapListener{
   
    private static final String DEBUG_TAG = "Gestures";
    private GestureDetectorCompat mDetector;

    // Called when the activity is first created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Instantiate the gesture detector with the
        // application context and an implementation of
        // GestureDetector.OnGestureListener
        mDetector = new GestureDetectorCompat(this,this);
        // Set the gesture detector as the double tap
        // listener.
        mDetector.setOnDoubleTapListener(this);
        // you can set other gesture listeners over here
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        // Be sure to call the superclass implementation
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent event) {
        Log.d(DEBUG_TAG,"onDown: " + event.toString());
        return true;
    }

    @Override
    public boolean onFling(MotionEvent event1, MotionEvent event2,
            float velocityX, float velocityY) {
        Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
        return true;
    }

    @Override
    public void onLongPress(MotionEvent event) {
        Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
            float distanceY) {
        Log.d(DEBUG_TAG, "onScroll: " + e1.toString()+e2.toString());
        return true;
    }

    @Override
    public void onShowPress(MotionEvent event) {
        Log.d(DEBUG_TAG, "onShowPress: " + event.toString());
    }

    @Override
    public boolean onSingleTapUp(MotionEvent event) {
        Log.d(DEBUG_TAG, "onSingleTapUp: " + event.toString());
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent event) {
        Log.d(DEBUG_TAG, "onDoubleTap: " + event.toString());
        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent event) {
        Log.d(DEBUG_TAG, "onDoubleTapEvent: " + event.toString());
        return true;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent event) {
        Log.d(DEBUG_TAG, "onSingleTapConfirmed: " + event.toString());
        return true;
    }
}

Android working with Volley Library - Http GET , POST , PUT , DELETE Request

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley offers the following benefits:

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence
  •  Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

 Following are the important class of volley:

  • RequestQueue: A Queue containing the Network/HTTP Requests that needs to be made.
  • Request: A Base Class which contains Network related information like HTTP Methods.
  • StringRequest: HTTP Request where the response is parsed a String. 
  • JsonObjectRequest: HTTP Request where the response is JSONObject.    

To use Volley, you must add the android.permission.INTERNET permission to your app's manifest. Without this, your app won't be able to connect to the network. 

Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "Url goes here"

Making GET Requests

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
                        // display response     
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
              //error
             Log.d("Error.Response", response);
       }
    }
);
 
// add it to the RequestQueue   
queue.add(getRequest);
 

Making POST Requests 

 
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {         // Adding parameters
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
             
            return params;  
    }
};
queue.add(postRequest);
 

Making PUT Requests 

 
StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
                         // error
             Log.d("Error.Response", response);
       }
    }
) {
 
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String> ();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
             
            return params;  
    }
 
};
 
queue.add(putRequest);
 

Making DELETE Requests

 
StringRequest deleteRequest = new StringRequest(Request.Method.DELETE, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error.
               Log.d("Error.Response", response);
       }
    }
);
queue.add(deleteRequest);
 
 
 








Sunday, 12 April 2015

Display Animated Gif Android

 
Step1)put a Gif image in drawable folder 
 
Step2)Make GifViewActivity and GifViewClass as follows

public class GifViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new GifViewClass(this));
    }

    private class GifViewClass extends View {
        Movie movie;

        GifViewClass(Context context) {
            super(context);
            //Gif image from drawable folder
            movie = Movie.decodeStream(
                    context.getResources().openRawResource(
                            R.drawable.gif_image));
        }
        @Override
        protected void onDraw(Canvas canvas) {   
            if (movie != null) {
                movie.setTime(
                    (int) SystemClock.uptimeMillis() % movie.duration());
                movie.draw(canvas, 0, 0);
                invalidate();
            }
        }
    }
}

Android animation using xml

Step to perform animation in android apps

Step 1) Create XML which define animation
create a xml file which define the animation in  res ⇒ anim ⇒ animation.xml , If you dont have anim folder then create it in res directory

blink.xml
<?xml version="1.0" encoding="utf-8"?>
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="800"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>
   
Step 2) Load the animation and set to view in acitvity to see blink effect

public class BlinkActivity extends Activity{
 
    TextView textMessage;
 
    // Animation
    Animation animBlink;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blink);
 
        textMessage = (TextView) findViewById(R.id.textMessage);
               textMessag.setText(Welcome to Android Code Portal);
        // load the animation
        animBlink = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.blink);  
       // start the animation
       textMessage.startAnimation(animBlink);
     
    }
}
 
Some other useful animations as follows
  
1)Blink
blink.xml
<?xml version="1.0" encoding="utf-8"?>
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="800"
        android:repeatMode="reverse"
        android:repeatCount="infinite"/>
</set>
 
2)ZoomIn
zoomin.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="3"
        android:toYScale="3" >
    </scale>
 
</set>
 
 3)ZoomOut
zoomout.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="0.5"
        android:toYScale="0.5" >
    </scale>
 
</set>
 
4)FadeIn
fadein.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <alpha
        android:duration="1000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
 
</set> 
 
5)FadeOut
fadeout.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="0.0" />
 
</set>
 
6)Rotate
rotate.xml
<?xml version="1.0" encoding="utf-8"?>
    <rotate android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="700"
        android:repeatMode="restart"
        android:repeatCount="infinite"
        android:interpolator="@android:anim/cycle_interpolator"/>
 
</set>
 
7)Move
 move.xml
<?xml version="1.0" encoding="utf-8"?>
<set
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">
 
   <translate
        android:fromXDelta="0%p"
        android:toXDelta="80%p"
        android:duration="1000" />
</set>
 
8)SlideDown
slidedown.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true">
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXScale="1.0"
        android:toYScale="1.0" />
 
</set>
 
 9)SlideUp
slideup.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true" >
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/linear_interpolator"
        android:toXScale="1.0"
        android:toYScale="0.0" />
 
</set>
 
10)Bounce
 bounce.xml
<?xml version="1.0" encoding="utf-8"?>
    android:fillAfter="true"
    android:interpolator="@android:anim/bounce_interpolator">
 
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
 
</set>