Show Settings Alert

    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

Detect Tap Count in Android

private int count = 0;
    private long startMillis=0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int eventaction = event.getAction();
        if (eventaction == MotionEvent.ACTION_UP) {

            //get system current milliseconds
            long time= System.currentTimeMillis();


            //if it is the first time, or if it has been more than 3 seconds since the first tap ( so it is like a new try), we reset everything
            if (startMillis==0 || (time-startMillis> 3000) ) {
                startMillis=time;
                count=1;
            }
            //it is not the first, and it has been  less than 3 seconds since the first
            else{ //  time-startMillis< 3000
                count++;
            }

            if (count==5) {
                 BrId = myPrefs.getInt("BrId", 0); // return 0 if someValue doesn't exist
                if(BrId != 0){
                    txtBrId.setText(String.valueOf(BrId));
                }
                txtBrId.setVisibility(View.VISIBLE);
                btnSaveBrId.setVisibility(View.VISIBLE);
                btnStartTracker.setVisibility(View.INVISIBLE);
            }
            return true;
        }
        return false;
    }

Show notification in android status bar

    private void ShowStatusBarNotification(String contentTitle,String contentText)
    {
        Notification notification = new Notification.Builder(getApplicationContext())
                .setContentTitle(contentTitle)
                .setContentText(contentText)
                .setSmallIcon(R.drawable.ic_statusbar_msg)
                .build();

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // notificationID allows you to update the notification later on.
        mNotificationManager.notify("BR Tracker",(int)(Math.random() * 101) ,notification);
    }

Working With ION In Android

//
//Android Code
//


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

//build.gradle (Module:app)
dependencies {
    ...
    compile group: 'com.koushikdutta.ion', name: 'ion', version: '2.1.6'
}

//MainActivity.java
    public void SubmitData(View view){

        JsonObject json = new JsonObject();
        json.addProperty("foo", "bar");
        json.addProperty("bar", "foo");
        try
        {
            Ion.with(getApplicationContext())
                    .load("http://182.160.99.115:1012/Home/SubmitData")
                    .setJsonObjectBody(json)
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {

                         String ServerSaid =  result.get("serversay").getAsString();

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

        }
        catch (Exception ex ){
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        }
    }
//
//ASP.NET MVC Code
//


namespace WorkingWithIon.Controllers
{
    public class HomeController : Controller
    {     
        public JsonResult SubmitData(string foo, string bar)
        {
            return Json(new{serversay=foo + " and " + bar}, JsonRequestBehavior.AllowGet);
        }
    }
}

Working with Camera in Android

//
//Taking a photo using camera, save in default camera location and show in ImageView 
control-
//

<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

public void TakePhoto(View view)
{
    Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
    {
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");

        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);
        imageView.setImageBitmap(bitmap);
    }
}

//
//Display photo from default Camera directory with a given name in an ImageView 
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public void ShowPhoto(View view)
{
    EditText PhotoNameTextbox=(EditText)findViewById(R.id.txtPhotoName);
    String PhotoName= PhotoNameTextbox.getText().toString() + ".jpg";

    //Get default camera directory
    File CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera"); // DIRECTORY_PICTURES

    //Photo path
    File photoFile= new File(CameraDirectory + File.separator + PhotoName);

    if (photoFile.exists())
    {
        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);

       //Following lines can be another option to show photo. Currently not required.
       /*Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
        imageView.setImageBitmap(bitmap);*/

       //Picasso is a third party library. http://square.github.io/picasso/
       Picasso.with(getApplicationContext()).load(photoFile).fit()
              .centerCrop().into(imageView);

    }
    else
    {
       Toast.makeText(DisplayPhoto.this, "Photo not found", Toast.LENGTH_SHORT).show();
     }
}

//
//Take a photo, Save with custom name, then display in ImageView
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public class TakePhotoAndSaveWithCustomNameAndPath extends AppCompatActivity
{
    File CameraDirectory;
    String photoName;
    static final int REQUEST_IMAGE_CAPTURE = 101;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo_and_save_with_custom_name_and_path);
        CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera");
    }
    
    public void TakePhoto(View view){
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        
        photoName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        Log.d("CustomPhotoName",photoName);
        File photo = new File(CameraDirectory, photoName + ".jpg");
        Uri uriSavedImage = Uri.fromFile(photo);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            try{
                ImageView imageView=(ImageView)findViewById(R.id.imageviewImage);
                File photo = new File(CameraDirectory, photoName + ".jpg");
                if(photo.exists()){
                    //Picasso is a third party library. http://square.github.io/picasso/
                    Picasso.with(getApplicationContext()).load(photo).fit().centerCrop().into(imageView);
                }
                else{
                    Log.d("PhotoFileStatus","Not found");
                }
            }
            catch (Exception ex){
                Log.d("PhotoError",ex.getMessage().toString());
                Toast.makeText(TakePhotoAndSaveWithCustomNameAndPath.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
            }

        }
    }
}

Android- Capture & Display Photo

MainActivity.java

package com.imslbd.firstcameraapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView txtChangeName;
    ImageView mImageView;
    static final int REQUEST_IMAGE_CAPTURE = 1;

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

       txtChangeName =(TextView) findViewById(R.id.txtDisplayName);
        mImageView=(ImageView) findViewById(R.id.imageView);
    }

    public  void ChangeName(View view)
    {
        dispatchTakePictureIntent();
        txtChangeName.setText("Hello");
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}

actiivity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android: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="com.imslbd.firstcameraapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/txtDisplayName" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/btnButton"
        android:layout_below="@+id/txtDisplayName"
        android:layout_alignParentStart="true"
        android:onClick="ChangeName" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnButton"
        android:layout_marginTop="41dp">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</RelativeLayout>


-------------------------------------------------------

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imslbd.firstcameraapp">

    <uses-feature android:name="android.hardware.camera"  android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Access Phonebook from Android App

package com.imslbd.ussdapp;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

    public void sendMessage(View view) {
        pickContact();
    }

    static final int PICK_CONTACT_REQUEST = 1;  // The request code

    private void pickContact() {
        Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
        pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
        startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request it is that we're responding to
        if (requestCode == PICK_CONTACT_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                // Get the URI that points to the selected contact
                Uri contactUri = data.getData();
                // We only need the NUMBER column, because there will be only one row in the result
                String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};

                // Perform the query on the contact to get the NUMBER column
                // We don't need a selection or sort order (there's only one result for the given URI)
                // CAUTION: The query() method should be called from a separate thread to avoid blocking
                // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
                // Consider using CursorLoader to perform the query.
                Cursor cursor = getContentResolver()
                        .query(contactUri, projection, null, null, null);
                cursor.moveToFirst();

                // Retrieve the phone number from the NUMBER column
                int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String number = cursor.getString(column);
                EditText etPhone= (EditText) findViewById(R.id.mymessage);
                etPhone.setText(number);
                // Do something with the phone number...
            }
        }
    }
}

Android Button Click Basic

        Button myButton= (Button) findViewById(R.id.mybutton);
        myButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                // Perform action on click
                EditText mytextbox= (EditText) findViewById(R.id.mytextbox);
                mytextbox.setText("Hello World");
            }
        });