. Android Developers Blog

Wednesday 17 February 2016

Android 3 Easy Steps to generate SHA1 and MD5 fingerprint| SHA-1 fingerprint of keystore certificate | Using Android Studio generate SHA-1 fingerprint

Hello Friends,
      Today, I am sharing few easy steps to generate SHA1 and MD5 fingerprint using
android studio.No need of terminal command, we can generate it in Android Studio
same as we did in Eclipse-->window---> preferences--->Android---->Build .

Here Are Steps with screen shot:

Easiest way :
  1. Open Android Studio
  2. Open Your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Option)
  4. Click on Refresh (Click on Refresh from Gradle, you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List (root))
  6. Click on Tasks
  7. Click on android
  8. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)

Screen 1.

Screen 2.



Screen 3.



All Done.


Hope this will help some one.
Enjoy Coding.....
Cheers :)

Monday 18 January 2016

Android RecyclerView and CardView tutorial | Android RecyclerView and CardView widgets | Android RecyclerView and CardView with backward compatibility

Hello Friends,
         Today, I am going to share my another post on Android RecyclerView and CardView.
This widgets come in android  latest release i.e Lollipop, Android 5.0 and API Level 21.
We can also add support on lower devices above API Level 7 by adding support library.
For creating complex Listview we need RecyclerView  and CardView.



Android RecyclerView: The advance version of Listview is RecyclerView, It is more
                                        advance and flexible. RecyclerView uses Layout manager for
managing position of item inside the recycler view. Recycler view provides three
built in Layout manager :

1. LinearLayoutManager : shows items in a vertical or horizontal scrolling list.
2. GridLayoutManager: shows items in a grid.
3. StaggeredGridLayoutManager: shows items in a staggered grid.

For more check this Link


CardView Widget:  It help us in showing information inside cards that have a consistent
                                  look across the platform. CardView widgets can have shadows and
                                  rounded corners.
 Note:
       1. To create a card with a shadow, use the card_view:cardElevation attribute. 
       2. To set the corner radius in your layouts, use the card_view:cardCornerRadius
           attribute.
      3. To set the corner radius in your code, use the CardView.setRadius method.
      4. To set the background color of a card, use the card_view:cardBackgroundColor
            attribute.


Here is Sample Code:

1. MainActivity.java

package solutions.developer.android.com.recyclerview;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Mukesh on 12/20/2015.
 */

public class MainActivity extends Activity {

    /**
     * Cursor used to access the results from querying for images
     * on the SD card.
     */
    private Cursor cursor;
    /*
     * Column index for the Thumbnails Image IDs.
     */
    private int columnIndex;
    private static final String TAG = "RecyclerViewExample";

    private List mediaList = new ArrayList();

    private RecyclerView mRecyclerView;

    private MediaRVAdapter adapter;

    String type = "";

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

        /* Initialize recyclerview */
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        type = "audio";
        new MediaAsyncTask().execute(type);

    }

    private void parseAllAudio(String type) {
        try {
          String TAG = "Audio";
          Cursor cur = getContentResolver().query(
                 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                  null);

          if (cur == null) {
              // Query failed...
              Log.e(TAG, "Failed to retrieve music: cursor is null :-(");
          } else if (!cur.moveToFirst()) {
             // Nothing to query. There is no music on the device. How boring.
              Log.e(TAG, "Failed to move cursor to first row (no query results).");
          } else {
              Log.i(TAG, "Listing...");
              // retrieve the indices of the columns where the ID,
              //title, etc. of the song are
              // add each song to mItems
             do {
                 int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                 int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                 int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                 int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                 int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
              int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                 Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                 Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: "
                 + cur.getString(titleColumn) + "Path: " +
                   cur.getString(filePathIndex));
                 MediaFileInfo audio = new MediaFileInfo();
                 audio.setFileName(cur.getString(titleColumn));
                 audio.setFilePath(cur.getString(filePathIndex));
                 audio.setFileType(type);
                 mediaList.add(audio);

              } while (cur.moveToNext());
          }

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

  public class MediaAsyncTask extends AsyncTask {

      @Overrid
      protected void onPreExecute() {
        //setProgressBarIndeterminateVisibility(true);
      }

     @Override
     protected Integer doInBackground(String... params) {
         Integer result = 0;
         String type = params[0];
         try {
             mediaList = new ArrayList();
              if (type.equalsIgnoreCase("audio")) {
                   parseAllAudio(type);
                   result = 1;
              }
        } catch (Exception e) {
              e.printStackTrace();
              result = 0;
        }
       return result; //"Failed to fetch data!";
   }
    @Override
    protected void onPostExecute(Integer result) {

      // setProgressBarIndeterminateVisibility(false);
      /* Download complete. Lets update UI */
      if (result == 1) {
          adapter = new MediaRVAdapter(MainActivity.this, mediaList);
          mRecyclerView.setAdapter(adapter);
      } else {
          Log.e(TAG, "Failed to fetch data!");
      }
   }
 }
} 

2. MediaRVAdapter.java

package solutions.developer.android.com.recyclerview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.List;

/**
 * Created by Mukesh on 12/20/2015.
 */
public class MediaRVAdapter extends RecyclerView.Adapter {


    private List itemList;

    private Context mContext;

    public MediaRVAdapter(Context context, List itemList) {
        this.itemList = itemList;
        this.mContext = context;
    }

    @Override
    public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, null);
        MediaListRowHolder mh = new MediaListRowHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
        try {
            MediaFileInfo item = itemList.get(i);
            mediaListRowHolder.title.setText(item.getFileName());
            Uri uri = Uri.fromFile(new File(item.getFilePath()));
            if (item.getFileType().equalsIgnoreCase("audio")) {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(item.getFilePath());
                try {
                    if (mmr != null) {
                        byte[] art = mmr.getEmbeddedPicture();
                        if (art != null && art.length > 0) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(art, 0, art.length);
                            if (bmp != null) {
                                bmp = ThumbnailUtils.extractThumbnail(bmp, 80, 50);
                                mediaListRowHolder.thumbnail.setImageBitmap(bmp);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }

    public class MediaListRowHolder extends RecyclerView.ViewHolder {
        protected ImageView thumbnail;
        protected TextView title;

        public MediaListRowHolder(View view) {
            super(view);
            this.thumbnail = (ImageView) view.findViewById(R.id.image);
            this.title = (TextView) view.findViewById(R.id.name);
        }
    }
} 


Download Complete Code from here

Hope this will help some one.....
Enjoy coding.......
Cheers  :)

Sunday 27 December 2015

Android media store tutorial | List all sdcard audio |List all sdcard video | List all sdcard images

Hello Friends,
       Today, I am going to share my another post on Android Media Store. In this post
I am going to show you how to query media file like audio,images and video using
Android Media Store and Android Content Resolver .









For Listing all Images:
private void parseAllImages() {
        try {
            String[] projection = {MediaStore.Images.Media.DATA};
            cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    null);

          
            int size = cursor.getCount();

            /*******  If size is 0, there are no images on the SD Card. *****/

            if (size == 0) {

            } else {

                int thumbID = 0;
                while (cursor.moveToNext()) {

                    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                    /**************** Captured image details ************/

                    /*****  Used to show image on view in LoadImagesFromSDCard class ******/
                    String path = cursor.getString(file_ColumnIndex);

                    String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());

                    MediaFileInfo mediaFileInfo = new MediaFileInfo();
                    mediaFileInfo.setFilePath(path);
                    mediaFileInfo.setFileName(fileName);
                    mediaFileInfo.setFileType(type);
                    mediaList.add(mediaFileInfo);
                }
            }


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


For Listing all Video(.mp4)


private void parseAllVideo() {
        try {
            String name = null;
            String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
                    MediaStore.Video.Thumbnails.VIDEO_ID};

            int video_column_index;
            String[] proj = {MediaStore.Video.Media._ID,
                    MediaStore.Video.Media.DATA,
                    MediaStore.Video.Media.DISPLAY_NAME,
                    MediaStore.Video.Media.SIZE};
            Cursor videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    proj, null, null, null);
            int count = videocursor.getCount();
            Log.d("No of video", "" + count);
            for (int i = 0; i < count; i++) {
                MediaFileInfo mediaFileInfo = new MediaFileInfo();
                video_column_index = videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                videocursor.moveToPosition(i);
                name = videocursor.getString(video_column_index);

                mediaFileInfo.setFileName(name);

                int column_index = videocursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                videocursor.moveToPosition(i);
                String filepath = videocursor.getString(column_index);

                mediaFileInfo.setFilePath(filepath);
                mediaFileInfo.setFileType(type);
                mediaList.add(mediaFileInfo);
                // id += " Size(KB):" +
                // videocursor.getString(video_column_index);


            }
            videocursor.close();

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



For Listing All Audio


private void parseAllAudio() {
        try {
            String TAG = "Audio";
            Cursor cur = getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    null);

            if (cur == null) {
                // Query failed...
                Log.e(TAG, "Failed to retrieve music: cursor is null :-(");

            }
            else if (!cur.moveToFirst()) {
                // Nothing to query. There is no music on the device. How boring.
                Log.e(TAG, "Failed to move cursor to first row (no query results).");

            }else {
                Log.i(TAG, "Listing...");
                // retrieve the indices of the columns where the ID, title, etc. of the song are

                // add each song to mItems
                do {
                    int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                    int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                    int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                    int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
                    int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                    Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                    Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: " + cur.getString(titleColumn) + "Path: " + cur.getString(filePathIndex));
                    MediaFileInfo audio = new MediaFileInfo();
                    audio.setFileName(cur.getString(titleColumn));
                    audio.setFilePath(cur.getString(filePathIndex));
                    audio.setFileType(type);
                    mediaList.add(audio);

                } while (cur.moveToNext());
            }

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




Downalod Complete Code: MediaListing


Hope this will help some one.
Enjoy coding..................  ;)

Saturday 19 December 2015

Android Turn on Bluetooth Tethering | Android enable tethering

Hello Friends ,
          Today, I am sharing my another blog on Bluetooth Tethering.  In this tutorial
we can programmatically turn on and off  Bluetooth Tethering.

 





















Here the code:

1. BluetoothTethering.java


package com.solutions.developer.android.com.bluetoothtethering;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


public class BluetoothTethering extends AppCompatActivity {

    BluetoothAdapter mBluetoothAdapter = null;
    Class classBluetoothPan = null;
    Constructor BTPanCtor = null;
    Object BTSrvInstance = null;
    Class noparams[] = {};
    Method mIsBTTetheringOn;
    public static Switch toggle ;

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

        toggle = (Switch) findViewById(R.id.wifi_switch);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    mBluetoothAdapter = getBTAdapter();
                    mBluetoothAdapter.enable();
                    Thread.sleep(100);
                    toggleTethering();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_bluetooth_tethering, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void toggleTethering() {
        Context MyContext = getApplicationContext();
        mBluetoothAdapter = getBTAdapter();
        String sClassName = "android.bluetooth.BluetoothPan";
        try {
            classBluetoothPan = Class.forName("android.bluetooth.BluetoothPan");
            mIsBTTetheringOn = classBluetoothPan.getDeclaredMethod("isTetheringOn", noparams);
            BTPanCtor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class);
            BTPanCtor.setAccessible(true);

            BTSrvInstance = BTPanCtor.newInstance(MyContext, new BTPanServiceListener(MyContext));
            Thread.sleep(250);

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

    @SuppressLint("NewApi")
    private BluetoothAdapter getBTAdapter() {
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
            return BluetoothAdapter.getDefaultAdapter();
        else {
            BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            return bm.getAdapter();
        }
    }

    public  static void changeToggleState(boolean state) {
        try{
            if(state){
                toggle.setChecked(BTPanServiceListener.state);
            }else {
                toggle.setChecked(BTPanServiceListener.state);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
 

2. BTPanServiceListener.java




package com.solutions.developer.android.com.bluetoothtethering;

import java.lang.reflect.InvocationTargetException;

import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class BTPanServiceListener implements BluetoothProfile.ServiceListener {
    private final Context context;
    public static boolean state = false;

    public BTPanServiceListener(final Context context) {
        this.context = context;
    }

    @Override
    public void onServiceConnected(final int profile,
                                   final BluetoothProfile proxy) {
        //Some code must be here or the compiler will optimize away this callback.
        Log.i("MyApp", "BTPan proxy connected");
        try {
            boolean nowVal = ((Boolean) proxy.getClass().getMethod("isTetheringOn", new Class[0]).invoke(proxy, new Object[0])).booleanValue();
            if (nowVal) {
                proxy.getClass().getMethod("setBluetoothTethering", new Class[]{Boolean.TYPE}).invoke(proxy, new Object[]{Boolean.valueOf(false)});
                Toast.makeText(context, "Turning bluetooth tethering off", Toast.LENGTH_SHORT).show();
                state = false;
            } else {
                proxy.getClass().getMethod("setBluetoothTethering", new Class[]{Boolean.TYPE}).invoke(proxy, new Object[]{Boolean.valueOf(true)});
                Toast.makeText(context, "Turning bluetooth tethering on", Toast.LENGTH_SHORT).show();
                state = true;
            }
            BluetoothTethering.changeToggleState(state);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(final int profile) {
    }
} 



Download Complete Code : BluetoothTethering

Hope this will help some one.
Enjoy coding....... :)

Tuesday 28 July 2015

Android Trusting all certificates using HttpClient over HTTPS| Access all secure and in-secure https connection in Android and Java

Hello Friends,
          Today, I am going to share a blog post on "HTTPS". Using this blog we can easily access all
secure and non secure "HTTPS" connection in java as well as android too.


1. Add "InSecureSSLSocketFactory.java" class

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;
public class InSecureSSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public InSecureSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
} 


2. Create a new HTTP client using the above InSecureSSLSocketFactory class, for making
     connection.

public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        InSecureSSLSocketFactory sf = new InSecureSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
3. Finally hitting the service url(https://) using getNewHttpClient() , which helps to feth data
    from server.

public static String networkHitForGetJsonData(String url)
{
 String websiteData = null;
 try {
  HttpParams httpParameters = new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
  HttpClient client = getNewHttpClient();
  URI uri = new URI(url);
  HttpGet method = new HttpGet(uri);
  method.addHeader("Content-Type", "text/html");
  HttpResponse res = client.execute(method);
  InputStream data = res.getEntity().getContent();
  websiteData = generateString(data);
  Log.e("response","response---> "+websiteData);
 } catch (ClientProtocolException e) {
  e.printStackTrace();
  websiteData = null;
 } catch (IOException e)
 {
  e.printStackTrace();
  websiteData = null;
 } catch (URISyntaxException e)
 {
  e.printStackTrace();
  websiteData = null;
 }
 return websiteData;
}  



Hope, this will helps some one.
Enjoy coding....... :)

Monday 6 July 2015

Android add calendar event Programatically | Android Codes: Insertion and Deletion of Calendar Events | Configure email notification with Calendar app in Android

Hello Friends,
          Today, I am sharing my another android tutorial which covers following things:

1. Android- Adding events to calendar via your android application
2. Programmatically add reminder in android calendara
3. Configure email notification with Calendar app in Android


A. For adding event on Calendar

try {
 String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
     // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
 // kind (which should remind me for whole day) 0 for false, 1
 // for true
  eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
   // confidential (1), private
   // (2), or public (3):
   // eventValues.put("transparency", 0); // You can control whether
   // an event consumes time
   // opaque (0) or transparent
   // (1).
 eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment()); 
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}


B. Set Reminder for above added event id:

if (needReminder) {
/***************** Event: Reminder(with alert) Adding reminder to event *******************/
        String reminderUriString = "content://com.android.calendar/reminders";
 ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value 
       //set time in min which occur before event start   
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)
 Uri reminderUri = curActivity.getApplicationContext()
      .getContentResolver()
    .insert(Uri.parse(reminderUriString), reminderValues);
}
 

C: Send mail to user for attending the meeting added on calendar

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";

 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
          // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
} 

D: For deletion of calendar event: Here "id" is event id.

Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(id));
getContentResolver().delete(uri, null, null); 

Finally All together: Add this method in your activity class

public long addAppointmentsToCalender(Activity curActivity, String title,
   String desc, String place, int status, long startDate,
   boolean needReminder, boolean needMailService) {
/***************** Event: add event *******************/
long eventID = -1;
try {
        String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
              // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
   // kind (which should remind me for whole day) 0 for false, 1
   // for true
 eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
                                      // confidential (1), private
                                      // (2), or public (3):
 // eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                          // opaque (0) or transparent (1).
   
        eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment());

 if (needReminder) {
 /***************** Event: Reminder(with alert) Adding reminder to event ***********        ********/
 
        String reminderUriString = "content://com.android.calendar/reminders";
        ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value of the
       // system. Minutes is a integer
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)

 Uri reminderUri = curActivity.getApplicationContext()
     .getContentResolver()
     .insert(Uri.parse(reminderUriString), reminderValues);
 }

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

 if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";
 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee Email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
        // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
 }
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}

return eventID;

}
 

Also need to add following permission in your AndroidManifest.xml file

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


Hope this will help some one.

Enjoy Coding :)

Tuesday 26 May 2015

Android Read Status Bar Notification | Android Read all incoming notification | Android Read Incoming Sms | Android Read Incoming Call

Hello Friends,
    Today, I am going to share a small tutorial on android "NotificationListenerService"
    which help us to read the all app notifications. This tutorial covers following
    points.

 




Feature:
1. We can easily read the notification of other android application or read all status bar
     notification,
2. Read|Listen incoming whatsapp messages
3. Read all incoming SMS
4. Read all incoming calls
5. Battery Low

Step1 : Create a Notification Service Class :
                    This class extends NotificationListenerService class which contains
                    two method:
                 a) onNotificationPosted(StatusBarNotification sbn) :
                           Implement this method to learn about new notifications as they are
                           posted by apps.
                 b) onNotificationRemoved(StatusBarNotification sbn) :
                           Implement this method to learn when notifications are removed.                         

 Note: The StatusBarNotifcation object contains extras, app package name and
            ticker name

1. NotificationService.java

package android.notifications;

import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;

import java.io.ByteArrayOutputStream;

/**
 * Created by mukesh on 19/5/15.
 */
public class NotificationService extends NotificationListenerService {

    Context context;

    @Override

    public void onCreate() {

        super.onCreate();
        context = getApplicationContext();

    }
    @Override

    public void onNotificationPosted(StatusBarNotification sbn) {
        String pack = sbn.getPackageName();
        String ticker ="";
        if(sbn.getNotification().tickerText !=null) {
            ticker = sbn.getNotification().tickerText.toString();
        }
        Bundle extras = sbn.getNotification().extras;
        String title = extras.getString("android.title");
        String text = extras.getCharSequence("android.text").toString();
        int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
        Bitmap id = sbn.getNotification().largeIcon;


        Log.i("Package",pack);
        Log.i("Ticker",ticker);
        Log.i("Title",title);
        Log.i("Text",text);

        Intent msgrcv = new Intent("Msg");
        msgrcv.putExtra("package", pack);
        msgrcv.putExtra("ticker", ticker);
        msgrcv.putExtra("title", title);
        msgrcv.putExtra("text", text);
        if(id != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            id.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            msgrcv.putExtra("icon",byteArray);
        }
        LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);


    }

    @Override

    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i("Msg","Notification Removed");

    }
}

2.MainActivity.java

package android.notifications;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import java.util.ArrayList;

/**
 * Created by mukesh on 19/5/15.
 */
public class MainActivity extends Activity {

    ListView list;
    CustomListAdapter adapter;
    ArrayList modelList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        modelList = new ArrayList();
        adapter = new CustomListAdapter(getApplicationContext(), modelList);
        list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(
                        "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private BroadcastReceiver onNotice= new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
           // String pack = intent.getStringExtra("package");
            String title = intent.getStringExtra("title");
            String text = intent.getStringExtra("text");
            //int id = intent.getIntExtra("icon",0);

            Context remotePackageContext = null;
            try {
//                remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
//                Drawable icon = remotePackageContext.getResources().getDrawable(id);
//                if(icon !=null) {
//                    ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
//                }
                byte[] byteArray =intent.getByteArrayExtra("icon");
                Bitmap bmp = null;
                if(byteArray !=null) {
                    bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                }
                Model model = new Model();
                model.setName(title +" " +text);
                model.setImage(bmp);

                if(modelList !=null) {
                    modelList.add(model);
                    adapter.notifyDataSetChanged();
                }else {
                    modelList = new ArrayList();
                    modelList.add(model);
                    adapter = new CustomListAdapter(getApplicationContext(), modelList);
                    list=(ListView)findViewById(R.id.list);
                    list.setAdapter(adapter);
                }

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

3. AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="android.notifications">
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="android.notifications.MainActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="android.notifications.NotificationService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SER                          VICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationLi                                  stenerService" />
            </intent-filter>
        </service>
        <receiver android:name="android.notifications.IncomingSms">
           <intent-filter>
               <action android:name="android.provider.Telephony.SMS_RECEIVED" />
           </intent-filter>
        </receiver>
        <receiver android:name=".ServiceReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>


4. Android check Notification Access Setting is enable or not:


//check notification access setting is enabled or not
public static boolean checkNotificationEnabled() {
         try{
       if(Settings.Secure.getString(MainActivity.mActivity.getContentResolver(),
                 "enabled_notification_listeners").contains(App.getContext().getPackageName())) 
      {
    return true;
      } else {
         return false;
      }

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



Download Complete Code From Here NotificationListener


Hope, this will helps someone.
Enjoy Coding .... :)

Monday 9 March 2015

Android applying custom fonts

Hello Friends,
      Today, I am sharing my small blog which helps you in applying custom fonts
on android text view from xml or styles file. Its very easy and reduces the number
of java line from your code and also make the performance of your app more better.
                                     


Steps:
1.Placed all your custom fonts file inside assets folder i.e: assets/fonts/digitalism.ttf)
2.Add the path of above custom font file your string.xml file
<string name="FONT_d3_digitalism">fonts/d3-digitalism.ttf</string>
<string name="FONT_digitalism">fonts/digitalism.ttf</string>
<string name="FONT_Mohave_Bold">fonts/Mohave-Bold.ttf</string>
<string name="FONT_Roboto_Black">fonts/Roboto-Black.ttf</string>
<string name="FONT_Roboto_Bold">fonts/Roboto-Bold.ttf</string>
<string name="FONT_Roboto_Medium">fonts/Roboto-Medium.ttf</string>
<string name="FONT_RobotoCondensed_Bold">fonts/RobotoCondensed-Bold.ttf</string>

3. Declartion of style inside values/styles.xml file for eg:
        <style name="CustomDigital">
          <item name="font">@string/FONT_digitalism</item>
        </style>

4. Inside attrs.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
      <declare-styleable name="Fontify">
<attr name="font" format="string" />
      </declare-styleable>

   <!-- Allows attribute use in an AppTheme definition -->
   <declare-styleable name="FontifyTheme">
<attr name="fontifyStyle" format="reference"/>
   </declare-styleable>
</resources>
5. finally, In our layout file we have to use this :
      <com.android.developer.solutions.font.TextClock
         android:id="@+id/textClock1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignLeft="@+id/btn"
         android:layout_alignRight="@+id/btn"
         android:layout_below="@+id/btn"
         android:layout_marginTop="20dp"
         android:gravity="center"
         android:textSize="18sp"
         style="@style/CustomDigital"
         android:text="TextClock" />


For more check below link:
https://github.com/danh32/Fontify


Download Demo Code : CustomTextFont

Hope this will help some one.
Enjoy Coding :)

Thursday 26 February 2015

Google Play Error Retrieving Information RPC:S-2:AEC-2 | How to Fix " Error retrieving information from server RPC:S-2:AEC-2"

Hello Friends ,                                                                              
                Yesterday, I am trying to download my app  
from Google Play Storebut Its give me the error
 "Error retrieving information from server RPC:S-2:AEC-2".
I was worried that may be the signed apk which I uploaded on
"Play store" was Tamper and Corrupted. But its not like
that, its  Google Play Services app  cache issue.


Here are the steps which I follow and then all works fine:

Step 1: Clear all cache and data
Go to  "Settings"  -> "Applications" -> "Manage Applications" -> "Google Play Services
Framework" and select "Clear Data" & "Clear Cache" to remove all the data.

Step 2: Restart your phone and then try to update and download app

Note: After Step 2 if you still facing the same issue then follow below step

Step 3: Remove and Add Your Google Play Store Account.

Go to "Settings" -> "Accounts" -> "Google" -> Select "Your Account" -> "Menu" and Select "Remove Account" and then "Add Your Account".

Now "Restart" your mobile device and try to perform update or download.


Hope this will help Some one....
Enjoy..... :)

Sunday 8 February 2015

Whats New in Android Lollipop | Android lollipop new features


Hello Friends,
       Today, I am sharing about the
  feature added android latest
 version i.e:"Android Lollipop".
                       



1. Material design
A bold, colorful and responsive UI design for consistent, intuitive experiences across all
your devices.

-Android 5.0 brings Material design to Android and gives you an expanded UI toolkit for
 integrating the new design patterns easily in your apps.
-New 3D views let you set a z-level to raise elements off of the view hierarchy and cast 
  real time shadows, even as they move.
- Ripple animations are available for buttons, checkboxes, and other touch controls in 
   your app.
- Animated and non-animated drawables based on XML vector graphics
- A new system-managed processing thread called RenderThread keeps animations 
  smooth even when there are delays in the main UI thread.  
- The RecyclerView widget 
- Drawable animation and styling effects
- Material design animation and activity transition effects


2. Notifications
New ways to control when and how you receive messages – only get interrupted when
you want to be.
       

- View and respond to messages directly from your
   lock screen. Includes the ability to hide sensitive 
   content for these notifications.
- For fewer disruptions, turn on Priority mode via 
  your device’s volume button so only certain people
  and notifications get through.
- Or schedule recurring downtime, such as from 10.00 p.m. until 
   8.00 a.m., when only  Priority notifications can get through.
- With Lollipop, incoming phone calls won’t interrupt what you’re watching or playing. 
   You can choose to answer the call or just keep doing what you’re doing.
- Control the notifications triggered by your apps; hide sensitive content and priorities or
    turn off the app’s notifications entirely.
- See all your notifications in one place by tapping the top of the screen.

3. Battery
    Power for the long haul

- A battery saver feature that extends device use by up to 90 mins.
- Estimated time left to fully charge is displayed when your device is plugged in.
- Estimated time left on your device before you need to charge again can now be found
   in battery settings.

4. Security
    Keep your stuff safe and sound

- New devices come with encryption automatically turned on to help protect data on lost
  or stolen devices.
- Use Android Smart Lock to secure your phone or tablet by pairing it with a trusted device
  like your wearable or even your car.

5. Device sharing
    More flexible sharing with family and friends

- Multiple users for phones. If you forget your phone, you still can call any of your
   friends (or access any of your messages, photos, etc.)  by simply logging in to 
   another Android phone running Lollipop. Also perfect for families who want to share a
   phone, but not their stuff.
- Guest user for phones and tablets means you can lend your device and not your info
- Screen pinning: pin your screen so that another user can access just that content 
   without messing with your other stuff

6. Accessibility
    Enhanced low-vision and colour-blind capabilities.

- Boost text contrast or invert colours to improve legibility.
- Adjust display to improve colour differentiation.  


7. Media
    Bolder graphics and improved audio, video and camera capabilities.

- Lower latency audio input ensuring that music and communication applications 
   that have strict delay requirements provide an amazing realtime experience.
- Multi-channel audio stream mixing means professional audio applications can now
   mix up to eight channels including 5.1 and 7.1 channels.
- USB Audio support means that you can plug USB microphones, speakers and a
   myriad of other USB audio devices like amplifiers and mixers into your Android device.
- OpenGL ES 3.1 and Android extension pack brings Android to the forefront of
   mobile graphics putting it on par with desktop and console class performance.

8. Runtime and performance
   A faster, smoother and more powerful computing experience.

- ART, an entirely new Android run time, improves application performance and
   responsiveness.
- Up to 4x performance improvements.
- Smoother UI for complex, visually rich applications.
- Compacting backgrounded apps and services so that you can do more at once.

9. Connectivity
    A better Internet connection everywhere and more powerful Bluetooth low energy capabilities

- Improved network handoffs resulting in limited interruption in connectivity. For 
  example, continue your video chat or VoIP calls without interruption as
  you leave the house and switch from your home Wi-Fi back to mobile.
- Improved network selection logic so that your device connects only if there is a 
   verified internet connection on Wi-Fi.
- Power-efficient scanning for nearby Bluetooth low energy (“BLE”) devices like 
   wearables or beacons.
- New BLE peripheral mode.

10. OK Google
Easy access to information and performing tasks

- Even if your screen is off, you can say "OK Google" on devices with digital signal
   processing support such as Nexus 6 and Nexus 9.
- Talk to Google on the go to get quick answers, send a text, get directions and more.

11. Coming soon: Android TV
            Support for living room devices

- User interface adapted for the living room.
- Less browsing, more watching with personalised recommendations for content like
   films and TV shows.
- Voice search for Google Play, YouTube and supported apps so that you can just 
   see what you want to see.
- Console-style Android gaming on your TV with a gamepad.
- Cast your favourite entertainment apps to your big screen with Google Cast support
   for Android TV devices.


for more check below linkss:
http://www.android.com/versions/lollipop-5-0/
http://developer.android.com/about/versions/android-5.0.html

 

Copyright @ 2013 Android Developers Blog.