Tuesday, 26 August 2014

Volley Network Image Loader

Hi All,

Volley is a library that handles the processing and caching of network requests. It helps to download the imaged from web asynchronously. We do not worry  about the Async Task to download the image from network because Volley library now can able to handle the image download asynchronously.

We already had known the famous library Universal Image Loder and Piccaso. Both are easy to handle to download the image in a thread pool and maintained the cache management.

Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
 Volley have lot of advantages:






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    • Automatic scheduling of network requests.
    • Multiple concurrent network connections.
    • Transparent disk and memory response caching
    • 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.
    • Application performance
    There are two available cache implementations. The recommended approach uses a basic in memory LRU cache. For the disk cache implementation I chose to use the DiskLruCache written by Jake Wharton. I chose this implementation because it is frequently used in the Android community and represents a common use case for someone trying to retrofit their application for Volley. Using a disk based L1 cache may cause i/o blocking issues. Volley already has an implicit disk L2 cache. The disk L1 cache is included because I was originally unaware of how Volley handled image request caching. 

    For download or clone of Volley library you have to run predefined command in your system, In your system should have installed the git.

    1. git clone https://android.googlesource.com/platform/frameworks/volley
    2. android update project -p .
    3. ant jar
    Once you done this commond you can get the volley clone library in your directory.
    Only thing you have to use the  NetworkImageView in place of ImageView. I have share code for GridView image loader with volley that manage the cache management for network processing.



      






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf

    activity_main.xml

    < RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="comsunil.volleygridexample.MainActivity" >
    
        
        
    
    < /RelativeLayout>
    

    grid_image_item.xml

    < ?xml version="1.0" encoding="utf-8"?>
    
    
    
        
    
    
    

    MainActivity.java

    package comsunil.volleygridexample;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;
    
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.NetworkImageView;
    
    public class MainActivity extends ActionBarActivity {
    
       ImageLoader mImageLoader;
       NetworkImageView mNetworkImageView;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      
      mImageLoader = MyVolleySingleton.getInstance(this).getImageLoader();
    
            final GridView gridView = (GridView) findViewById(R.id.gridView);
            gridView.setAdapter(new MyImageAdapter());
    
            
     }
    
      static class ViewHolder {
             ImageView imageView;
         }
    
         class MyImageAdapter extends BaseAdapter {
    
             @Override
             public int getCount() {
                 return ImageUrlArray.IMAGES.length;
             }
    
             @Override
             public Object getItem(int position) {
                 return null;
             }
    
             @Override
             public long getItemId(int position) {
                 return position;
             }
    
             @Override
             public View getView(int position, View convertView, ViewGroup parent) {
    
                 View view = convertView;
                 final ViewHolder gridViewImageHolder;
    //             check to see if we have a view
                 if (view == null) {
                     view = getLayoutInflater().inflate(R.layout.grid_image_item, parent, false);
                     gridViewImageHolder = new ViewHolder();
                     gridViewImageHolder.imageView = (ImageView) view.findViewById(R.id.networkImageView);
                     view.setTag(gridViewImageHolder);
                 } else {
                     gridViewImageHolder = (ViewHolder) view.getTag();
                 }
    
                 mNetworkImageView = (NetworkImageView) gridViewImageHolder.imageView;
                 mNetworkImageView.setDefaultImageResId(R.drawable.no_image);
                 mNetworkImageView.setErrorImageResId(R.drawable.error);
                 mNetworkImageView.setAdjustViewBounds(true);
                 mNetworkImageView.setImageUrl(ImageUrlArray.IMAGES[position], mImageLoader);
    
                 return view;
             }
         }
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
       return true;
      }
      return super.onOptionsItemSelected(item);
     }
    }
    
    

    MyVolleySingleton.java

    package comsunil.volleygridexample;
    
    import android.content.Context;
    
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.Volley;
    
    /**
     * copied from the official documentation
     */
    public class MyVolleySingleton {
    
        private static MyVolleySingleton mVolleyInstance;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;
        private static Context mContext;
    
        private MyVolleySingleton(Context context) {
            mContext = context;
            mRequestQueue = getRequestQueue();
            mImageLoader = new ImageLoader(mRequestQueue,
                    new MyLruBitmapCache(MyLruBitmapCache.getCacheSize(context))
            );
        }
    
        public static synchronized MyVolleySingleton getInstance(Context context) {
            if (mVolleyInstance == null) {
                mVolleyInstance = new MyVolleySingleton(context);
            }
            return mVolleyInstance;
        }
    
        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                // use the application context
                mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
            }
            return mRequestQueue;
        }
    
        public  void addToRequestQueue(Request req) {
            getRequestQueue().add(req);
        }
    
        public ImageLoader getImageLoader() {
            return mImageLoader;
        }
    }
    
    

    MyLruBitmapCache.java

    package comsunil.volleygridexample;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.support.v4.util.LruCache;
    import android.util.DisplayMetrics;
    
    import com.android.volley.toolbox.ImageLoader;
    
    /**
     * copied from official documentation
     */
    public class MyLruBitmapCache extends LruCache
            implements ImageLoader.ImageCache {
    
        public MyLruBitmapCache(int maxSize) {
            super(maxSize);
        }
    
        public MyLruBitmapCache(Context ctx) {
            this(getCacheSize(ctx));
        }
    
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    
        @Override
        public Bitmap getBitmap(String url) {
            return get(url);
        }
    
        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            put(url, bitmap);
        }
    
        // Returns a cache size equal to approximately three screens worth of images.
        public static int getCacheSize(Context ctx) {
            final DisplayMetrics displayMetrics = ctx.getResources().
                    getDisplayMetrics();
            final int screenWidth = displayMetrics.widthPixels;
            final int screenHeight = displayMetrics.heightPixels;
            // 4 bytes per pixel
            final int screenBytes = screenWidth * screenHeight * 4;
    
            return screenBytes * 3;
        }
    }
    

    For network operation I recommended to use this library instead of AsynTask.

    package com.sunil.volleynetworkoperation;
    
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.TextView;
    
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;
    
    public class MainActivity extends Activity {
    
     private TextView txtDisplay;
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      txtDisplay = (TextView) findViewById(R.id.txtDisplay);
      
      RequestQueue queue = Volley.newRequestQueue(this);
      String url = "http://echo.jsontest.com/key/value/one/two";
      
      JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
    
       @Override
       public void onResponse(JSONObject response) {
        // TODO Auto-generated method stub
        txtDisplay.setText("Response => "+response.toString());
        findViewById(R.id.progressBar1).setVisibility(View.GONE);
       }
      }, new Response.ErrorListener() {
    
       @Override
       public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        
       }
       
      
      })
      
      
      /*{       // if you have any key value request
          @Override
          protected Map getParams() 
          {  
                  Map  params = new HashMap();  
                  params.put("name", "sunil");  
                  params.put("domain", "http://sunil.info");
                   
                  return params;  
          }
      }*/;
      
      queue.add(jsObjRequest);
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
       return true;
      }
      return super.onOptionsItemSelected(item);
     }
    }
    
    
    Here you can dwonload the source code VolleyGridview

    Monday, 14 July 2014

    CalenderView Example

    Hi Guys,

    Today I am sharing the code for CalenderView. This class is a calendar widget for displaying and selecting dates. The range of dates supported by this calendar is configurable. A user can select a date by taping on it and can scroll and fling the calendar to a desired date.

    activity_main.xml

    
    
        
    
    
    
    

    MainActivity.java

    package com.sunil.calenderexample;
    
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.CalendarView;
    import android.widget.CalendarView.OnDateChangeListener;
    import android.widget.Toast;
    
    public class MainActivity extends ActionBarActivity implements OnDateChangeListener {
    
     private CalendarView calenderview=null;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      calenderview=(CalendarView)findViewById(R.id.calendarView_cl);
      calenderview.setOnDateChangeListener(this);
      
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
       return true;
      }
      return super.onOptionsItemSelected(item);
     }
    
     @Override
     public void onSelectedDayChange(CalendarView arg0, int arg1, int arg2, int arg3) {
      
      Toast.makeText(getBaseContext(), arg1+"/"+arg2+"/"+arg3, Toast.LENGTH_LONG).show();
     }
    }
    
    

    Result is:
    Here you can download the source code CalenderView Example

    Saturday, 21 June 2014

    Check Network Connectivity

    Hi Guys,

    I am sharing the code for check the internet connectivity of your device either mobile or wifi connectivity.
    More detail Here 
    Java Code:
      private void checkNetworkConnection() {
          ConnectivityManager connMgr =
              (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
          if (activeInfo != null && activeInfo.isConnected()) {
              wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
              mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
              if(wifiConnected) {
                  Log.i(TAG, "WIFI connected");
              } else if (mobileConnected){
                  Log.i(TAG, "Mobile Connected");
              }
          } else {
              Log.i(TAG,"Neither Mobile nor WIFi connected.");
          }
        }
     
    or second way
     public static boolean isInternetOn(Context context) {
      ConnectivityManager cm = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
      // test for connection
      if (cm.getActiveNetworkInfo() != null
        && cm.getActiveNetworkInfo().isAvailable()
        && cm.getActiveNetworkInfo().isConnected()) {
       Log.v("Util", "Internet is working");
       // txt_status.setText("Internet is working");
       return true;
      } else {
       // txt_status.setText("Internet Connection Not Present");
       Log.v("Util", "Internet Connection Not Present");
       return false;
      }
     }
     
    Please do not forget to add the permission in AndroidMenifest file.
     
     
     
    

    Monday, 4 November 2013

    Multiple Row Item Deleted from Listview Android

    Hi Guys!!

    First of all Happy Diwali to all my friends and fans.

    In this article we are learning the new android API concept that delete the multiple  row item of the list view.
    Before we have knowledge about the delete the row item with the help of check box. But in new API-18 have provide the features to delete the multiple row item from the list-view without the check-box uses.

    This feature is available inside the contextual action mode in higher android version 3.0. So here question is what is contextual action mode?
    The contextual action mode is a system implementation of ActionMode that focuses user interaction toward performing contextual actions. When a user enables this mode by selecting an item, a contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected item(s). While this mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue to navigate within the activity (as much as you're willing to allow). The action mode is disabled and the contextual action bar disappears when the user deselects all items, presses the BACK button, or selects the Done action on the left side of the bar.

    This event happen when the user performs a long-click on the view.  Contextual actions on groups of items in a ListView or GridView (allowing the user to select multiple items and perform an action on them all).
    More details about this contextual menu. and MultiChoiceModeListener.

    So lets start the to coding to see this features.


    main_activity.xml

    
    
        
        
        
    
    
     
    

    MainActivity.java

    package com.sunil.listviewmuntilerowdelete;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.util.SparseBooleanArray;
    import android.view.ActionMode;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.AbsListView.MultiChoiceModeListener;
    import android.widget.ListView;
    
    @SuppressLint("NewApi")
    public class MainActivity extends Activity implements MultiChoiceModeListener{
    
      private String[] myfriendname=null;
      private String[] myfriendnickname=null;
      private int[] photo=null;
      ListView listView=null;
      Context contex=null;
      MyListAdapter adapter=null;
      private List list=new ArrayList();
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      contex=this;
      listView = (ListView) findViewById(R.id.listview);
      
      myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi","Sandeep Pal", "Amit Verma" };
            myfriendnickname = new String[] { "sunil android", "Abhi cool","Sandy duffer", "Budhiya jokar"};
            photo = new int[] { R.drawable.sunil, R.drawable.abhi, R.drawable.sandy, R.drawable.amit};
         
            for(int index=0; index< myfriendname.length; index++){
             MyFriendsSDetails details=new MyFriendsSDetails(myfriendname[index], myfriendnickname[index], photo[index]);
             list.add(details);
            }
            
            adapter=new MyListAdapter(contex, list);
            listView.setAdapter(adapter);
            listView.setMultiChoiceModeListener(this);
            listView.setChoiceMode(listView.CHOICE_MODE_MULTIPLE_MODAL);
     
     }
     @Override
     public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
      switch (arg1.getItemId()) {
      case R.id.delete:
       SparseBooleanArray selected = adapter.getSelectedIds();
       for (int i = (selected.size() - 1); i >= 0; i--) {
        if (selected.valueAt(i)) {
         MyFriendsSDetails selecteditem = adapter.getItem(selected.keyAt(i));
         adapter.remove(selecteditem);
        }
       }
       // Close CAB
       arg0.finish();
       return true;
       default:
        return false;
      } 
       }
     @Override
     public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
      arg0.getMenuInflater().inflate(R.menu.main, arg1);
      return true;
      
     }
     @Override
     public void onDestroyActionMode(ActionMode arg0) {
      adapter.removeSelection();
     }
     @Override
     public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
      return false;
     }
     @Override
     public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2, boolean arg3) {
      
      final int checkedCount = listView.getCheckedItemCount();
      arg0.setTitle(checkedCount + " Selected");
      adapter.toggleSelection(arg1);
     }
    
    }
    
    

    MyFriendsSDetails.java

    package com.sunil.listviewmuntilerowdelete;
    
    public class MyFriendsSDetails {
     
      private String myfriendname=null;
      private String myfriendnickname=null;
      private int photo=0;
      
      public MyFriendsSDetails(String friendname, String friendnickname, int myphoto){
       this.myfriendname=friendname;
       this.myfriendnickname=friendnickname;
       this.photo=myphoto;
      }
    
     public String getMyfriendname() {
      return myfriendname;
     }
    
     public void setMyfriendname(String myfriendname) {
      this.myfriendname = myfriendname;
     }
    
     public String getMyfriendnickname() {
      return myfriendnickname;
     }
    
     public void setMyfriendnickname(String myfriendnickname) {
      this.myfriendnickname = myfriendnickname;
     }
    
     public int getPhoto() {
      return photo;
     }
    
     public void setPhoto(int photo) {
      this.photo = photo;
     }
    
      
    }
    
    

    list_item.xml

    
    
        
    
        
    
            
    
            
        
    
    
    

    MyListAdapter.java

    package com.sunil.listviewmuntilerowdelete;
    
    import java.util.List;
    
    import android.content.Context;
    import android.util.SparseBooleanArray;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyListAdapter extends ArrayAdapter{
     
     Context context;
     LayoutInflater inflater;
     List list;
     private SparseBooleanArray mSelectedItemsIds;
     
     public MyListAdapter(Context context, List list) {
      super(context, 0, list);
      mSelectedItemsIds = new SparseBooleanArray();
      this.context = context;
      this.list = list;
      inflater = LayoutInflater.from(context);
     }
    
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
      
      final ViewHolder holder;
      if (convertView == null) {
       holder = new ViewHolder();
       convertView = inflater.inflate(R.layout.list_item, null);
       holder.name = (TextView) convertView.findViewById(R.id.title);
       holder.nickname = (TextView) convertView.findViewById(R.id.subtitle);
       holder.photo = (ImageView) convertView.findViewById(R.id.icon);
       convertView.setTag(holder);
      } else {
       holder = (ViewHolder) convertView.getTag();
      }
      holder.name.setText(list.get(position).getMyfriendname());
      holder.nickname.setText(list.get(position).getMyfriendnickname());
      holder.photo.setImageResource(list.get(position).getPhoto());
      return convertView;
     }
     
     public void toggleSelection(int position) {
      selectView(position, !mSelectedItemsIds.get(position));
     }
    
     public void selectView(int position, boolean value) {
      if (value)
       mSelectedItemsIds.put(position, value);
      else
       mSelectedItemsIds.delete(position);
      notifyDataSetChanged();
     }
     
     public void removeSelection() {
      mSelectedItemsIds = new SparseBooleanArray();
      notifyDataSetChanged();
     }
     
     public SparseBooleanArray getSelectedIds() {
      return mSelectedItemsIds;
     }
     private class ViewHolder {
      TextView name;
      TextView nickname;
      ImageView photo;
     }
    }
    
    Screen shot:


    You can download the full source code ListViewMultipleRowDelete and here

    Cheers Guys!!

    Sunday, 13 October 2013

    Alarm via BoardCast Reciever Android

    Hi Guys,

    This tutorial might be helpful for leaning about the Alarm with Broadcast Receiver in android.
    A Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android run-time once this event happens. 

    A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

    If registering a receiver in your Activity.onResume() implementation, you should unregistered it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregistered in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.  More detail about broadcast receiever Here.

    Alarm Manager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

    The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

    There are two way we can registered and unregistered the broadcast receive.
    1. Dynamic way
    2. Static Way 

    Dynamic way:-

    You can register a receiver dynamically via the Context.registerReceiver() method. You can also dynamically unregister receiver by using Context.unregisterReceiver() method.

    Static Way:-

    You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.
    For Register
    ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
    PackageManager pm = this.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    
    For UnRegister
    ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
    PackageManager pm = this.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
    

    main_activity.xml

    
    
        
    

    MainActivity.java

    package com.sunil.br;
    
    import android.app.Activity;
    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends Activity implements OnClickListener{
    
    	private Button btnstartalarm=null;
    	private Button btncancelalarm=null;
    	private Button btnenablebr=null;
    	private Button btndiablebr=null;
    	AlarmManager amanager=null;
    	PendingIntent pi=null;
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    	
    		btnstartalarm = (Button)findViewById(R.id.button_startalarm);
    		btncancelalarm = (Button)findViewById(R.id.button_cancelalarm);
    		btnenablebr = (Button)findViewById(R.id.button_enablebr);
    		btndiablebr = (Button)findViewById(R.id.button_disablebr);
    		
    		btnstartalarm.setOnClickListener(this);
    		btndiablebr.setOnClickListener(this);
    		btncancelalarm.setOnClickListener(this);
    		btnenablebr.setOnClickListener(this);
    		
    	}
    
    	@Override
    	public void onClick(View arg0) {
    		
    		if(arg0==btnstartalarm)
    		{
    			amanager=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    			Intent intent= new  Intent(this, AlarmManagerBR.class);
    		    pi=PendingIntent.getBroadcast(this, 0, intent, 0);
    			 //After after 2 seconds
    			amanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*4, pi);
    			Toast.makeText(this, "Start Repating Alarm", Toast.LENGTH_SHORT).show();
    			
    		}
    		else if (arg0==btncancelalarm) {
    			
    			amanager.cancel(pi);
    			Toast.makeText(this, "Canceled Alarm", Toast.LENGTH_SHORT).show();
    		}
    		
    		else if(arg0==btnenablebr){
    			
    			 ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
    			 PackageManager pm = this.getPackageManager();
                 pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
                 Toast.makeText(this, "Enable Boradcast Reciever", Toast.LENGTH_SHORT).show();
    		}
    		else if (arg0==btndiablebr) {
    			
    			 ComponentName receiver = new ComponentName(this, AlarmManagerBR.class);
    			 PackageManager pm = this.getPackageManager();
                 pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
                 Toast.makeText(this, "Diable Boradcast Reciever", Toast.LENGTH_SHORT).show();
    		}
    	}
    }
    
    

    AlarmManagerBR.java

    package com.sunil.br;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import android.annotation.SuppressLint;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;
    
    public class AlarmManagerBR extends BroadcastReceiver{
    
    	@SuppressLint("SimpleDateFormat")
    	@Override
    	public void onReceive(Context arg0, Intent arg1) {
    		
    		StringBuilder sb=new StringBuilder();
    		SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss a");
    		sb.append(format.format(new Date()));
    		Toast.makeText(arg0, sb, Toast.LENGTH_SHORT).show();
    	}
    
    }
    
    

    Manifest.xml

    
    
        
    
        
            
                
                    
    
                    
                
            
            
        
    
    
    

    You can download the source code BoradCastRecieverExample
    Cheers Guys!!

    Saturday, 5 October 2013

    Insert And Retrieve Image into DB

    Hi Guys,

    In this tutorial we are sharing the code to insert the image into db and retrieve the image from db. I hope this article might be helpful to all learning developer.

    SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.

    Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

    Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

    For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.
    An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
    The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

    But i think in big level storing the image in database is not valuable because database sqlite have limited space so store the image path is valuable.

    main_activity.xml

    
    
        
    
        
    
        
    

    MainActivity.java

    package com.sunil.insertimageindb;
    
    import java.io.ByteArrayOutputStream;
    
    import com.sunil.insertimageindb.R;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity implements OnClickListener{
    
    	private ImageView imageview=null;
    	private Button btninsert=null;
    	private Button btnretrive=null;
    	private MyDataBase mdb=null;
    	private SQLiteDatabase db=null;
    	private Cursor c=null;
    	private byte[] img=null;
    	private static final String DATABASE_NAME = "ImageDb.db";
    	public static final int DATABASE_VERSION = 1;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		btninsert=(Button)findViewById(R.id.button_insert);
    		btnretrive= (Button)findViewById(R.id.button_retrieve);
    		imageview= (ImageView)findViewById(R.id.imageView_image);
    		imageview.setImageResource(0);
    		btninsert.setOnClickListener(this);
    		btnretrive.setOnClickListener(this);
    		mdb=new MyDataBase(getApplicationContext(), DATABASE_NAME,null, DATABASE_VERSION);
    	   
    
            Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.PNG, 100, bos);
            img=bos.toByteArray();
            db=mdb.getWritableDatabase();
    	}
    	@Override
    	public void onClick(View arg0) {
    		
    		if(btninsert==arg0)
    		{
    			ContentValues cv=new ContentValues();
    	        cv.put("image", img);
    	        db.insert("tableimage", null, cv);
    	        Toast.makeText(this, "inserted successfully", Toast.LENGTH_SHORT).show();
    		}
    		else if(btnretrive==arg0)
    		{
    			    String[] col={"image"};
    		        c=db.query("tableimage", col, null, null, null, null, null);
    		       
    		        if(c!=null){
    		            c.moveToFirst();
    		            do{
    		                img=c.getBlob(c.getColumnIndex("image"));
    		               }while(c.moveToNext());
    		        }
    		        Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);
    		     
                     imageview.setImageBitmap(b1);
                     Toast.makeText(this, "Retrive successfully", Toast.LENGTH_SHORT).show();
    		    }
    		}
    
    }
    

    MyDatabase.java

    package com.sunil.insertimageindb;
    
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    
    public class MyDataBase extends SQLiteOpenHelper{
    	
        public MyDataBase(Context context, String dbname, CursorFactory factory, int dbversion) {
            super(context, dbname, factory, dbversion);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table tableimage(image blob);");
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           
        }
    
    }
    

    Store the image in db looks like that


    You can download the source code InsertImageintoDB.
    Cheers Guys!!

    Wednesday, 2 October 2013

    PayPal Android SDK With Multiple In-App Payment

    Hi Guys,

    I hope this tutorial and article might be helpful for all android developer to make a multiple payment with this new android sdk pay pal in app.
    PayPal announced a new Android SDK that tries to make it easier for developers to accept in-app payments on Google’s mobile platform.
    As expected, the Android payments solution accepts both PayPal and credit card payments. The company says it is quick and easy to use, and “removes payment friction so developers can focus on creating amazing experiences.”

    PayPal’s strategy is to make it as easy as possible for mobile developers to integrate its payments into their work. The pitch is simple: if consumers don’t have to leave your app to pay, and they can do so in more ways than one (click a PayPal button or scan a credit/debit card), they will be more likely to do so.

    The new PayPal Android SDK supports Android version 2.2 and up. The new Android payment solution will allow developers to accept payments via PayPal and via credit cards. PayPal believes that giving users the option to pay quickly and easily via their PayPal account or by scanning a credit card will lure more customers into paying developers for their work.

    PayPal says that it is also offering security features that will allow developers to “significantly reduce” fraud they encounter with payments. So I think that its really amazing concept for android developer.
    More in detail visit the pay pal developer site and git-hub repository Pay Pay Developer.

     
     

    main_activity.xml

    
    
        
    

    MainActivity.java

    package com.paypal.sunil.paypalandroidsdk;
    
    import java.math.BigDecimal;
    
    import org.json.JSONException;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    
    import com.paypal.android.sdk.payments.PayPalPayment;
    import com.paypal.android.sdk.payments.PayPalService;
    import com.paypal.android.sdk.payments.PaymentActivity;
    import com.paypal.android.sdk.payments.PaymentConfirmation;
    
    public class MainActivity extends Activity {
        
        // set to PaymentActivity.ENVIRONMENT_LIVE to move real money.
        // set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
        // set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.
        private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;
        
        // note that these credentials will differ between live & sandbox environments.
        private static final String CONFIG_CLIENT_ID = "credential from developer.paypal.com";
        // when testing in sandbox, this is likely the -facilitator email address. 
        private static final String CONFIG_RECEIVER_EMAIL = "matching paypal email address"; 
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            Intent intent = new Intent(this, PayPalService.class);
            
            intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
            intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
            intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
            
            startService(intent);
        }
    
        public void onBuyPressed(View pressed) {
            PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans");
            
            Intent intent = new Intent(this, PaymentActivity.class);
            
            intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
            intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
            intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
            
            // It's important to repeat the clientId here so that the SDK has it if Android restarts your 
            // app midway through the payment UI flow.
            intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
            intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
            intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
            
            startActivityForResult(intent, 0);
        }
        
        @Override
        protected void onActivityResult (int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i("paymentExample", confirm.toJSONObject().toString(4));
    
                        // TODO: send 'confirm' to your server for verification.
                        // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                        // for more details.
    
                    } catch (JSONException e) {
                        Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            }
            else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("paymentExample", "The user canceled.");
            }
            else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
                Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
            }
        }
        
        @Override
        public void onDestroy() {
            stopService(new Intent(this, PayPalService.class));
            super.onDestroy();
        }
    }
    

    Manifest.xml

    
    
        
        
        
        
        
        
        
        
    
        
        
        
        
    
        
            
                
                    
    
                    
                
            
            
            
            
            
            
            
            
            
            
            
            
        
    
    
    






    You can download the source code PaypalSDK