Wednesday, August 31, 2016

Service and It's Life cycle

Hi .... Dear All ....  Today I am uploading a superb example of Service with it's life cycle.

Service
@ It's an Application component  which has 
1. Activity which has No layout
2. Running in Background
3.  Used for long running task
4. Service has it’s life cycle

Drawback 
@ It's running with main thread so we should use asynctask with service

Type

1. Started      2. Bound 

@ To create a service, you must create a subclass of Service.
@ In your implementation, you need to override some callback methods that handle key aspects of the      service lifecycle and provide a mechanism for components to bind to the service.
@ Callback methods are onCreate(),onStartCommand(),onBind(),onDestroy().
See the below example -  Register your service in manifest file 
like   <service android:name=".MyServ"></service>

A. Output will be like  


B. XML file     activity_main.xml is as 
<?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"

    tools:context="com.exam.ravi.servicedemo.MainActivity">

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="StartService"

        android:id="@+id/button1"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="44dp"

        android:onClick="startServ"

        android:layout_toStartOf="@+id/button2"     />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="StopService"

        android:id="@+id/button2"

        android:onClick="stopServ"

        android:layout_alignTop="@+id/button1"

        android:layout_alignParentEnd="true" />
  
</RelativeLayout>

C. Java Code is as 
   C - 1     Service class is as   MyServ.java
   package com.exam.ravi.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class MyServ extends Service
{
    @Nullable    @Override    public IBinder onBind(Intent intent)   
                                  // Used for Bind service Local or Remote    {
        return null;
    }


    @Override    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"onstartcommand called",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"onCreate called",Toast.LENGTH_LONG).show();
    }

    @Override    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"onDestroy called",Toast.LENGTH_LONG).show();
    }
}

C - 2  MainActivity.java is as 

package com.exam.ravi.servicedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    Intent iob;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iob=new Intent(this,MyServ.class);
    }
    public void startServ(View v)

    {
    startService(iob);
    }
    public void stopServ(View v)
    {
       stopService(iob);
    }
}



Sunday, August 28, 2016

Rendering Surface Using SurfaceView and SurfaceHolder @ Story Behind Camera App

Hi .... Dear All ....  Today I am uploading a superb example of how Image render on Surface.
This concept is implemented by extending SurfaceView Class and implementing SurfaceHolder Callback Methods.
We have to use Camera of the device so add the below permission in manifest file 
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
SurfaceView
@ Provides a dedicated drawing surface embedded inside of a view hierarchy. 
One of the purposes of this class is to provide a surface in which a secondary thread can
     render into the screen.
@ One of the purposes of this class is to provide a surface in which a secondary thread can
     render into the screen.
 I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box

A. Output Will be  -  Output will render on the screen if you click it will be like 

B. Java Code 
1.    MainActivity.java will be  like 
package com.exam.ravi.surfaceviewex1;
import android.hardware.Camera;
import android.hardware.Camera.ErrorCallback;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
@SuppressWarnings("ALL")
public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "RenderDemo";
    private RenderPreview renderPreview;
    @Override    public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         Camera camera = Camera.open();
         renderPreview = new RenderPreview(this, camera);
         renderPreview.camera.setErrorCallback(new ErrorCallback()
         {
             @Override             public void onError(int error, Camera camera)
             {
                 System.out.println("Error in camera -- " + error);
             }
         });
         setContentView(renderPreview);
     }
}

2. RenderPreview.java is like 

package com.exam.ravi.surfaceviewex1;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
@SuppressWarnings("ALL")
class RenderPreview extends SurfaceView implements SurfaceHolder.Callback
{
    private static final String TAG = "RenderPreview";
    SurfaceHolder surfaceHolder;
    public Camera camera;
    public byte[] cameraData;
    RenderPreview(Context context, Camera camera)
    {
        super(context);
        this.camera = camera;
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    // Called once the holder is ready

     public void surfaceCreated(SurfaceHolder holder)
     {
        // The Surface has been created, acquire the camera and tell it where  to draw.

                try {
                    camera.setPreviewDisplay(holder);
                    camera.setPreviewCallback(new PreviewCallback() {
                        // Called for each frame previewed

                    public void onPreviewFrame(byte[] data, Camera camera)
                        {
                            cameraData = data;
                            Log.d(TAG, "Size of camera Data - " + cameraData.length);
                            RenderPreview.this.invalidate();
                        }
                    });
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
     }
    // Called when surface holder is destroyed
   
     public void surfaceDestroyed(SurfaceHolder holder)
    {
        holder.removeCallback(this);
    }
    // Called when surface holder has changed
    
      public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        try        {
            camera.startPreview();
        }
        catch (RuntimeException e)
        {
            Log.e("CameraPreview", "Runtime Exeption " + e.getLocalizedMessage());
        }
    }
}

Drawing on Canvas - Extending View

Hi .... Dear All ....  Today I am uploading a superb example of how Drawing on Canvas by Extending View Class.
Canvas 
@The Canvas class holds the "draw" calls.
The Four Basic Components are 
1.  A Bitmap to hold the pixels, 
2. Canvas to host the draw calls (writing into the bitmap)
3.Drawing primitive (e.g. Rect, Path, text, Bitmap)
4.Paint (to describe the colors and styles for the drawing).

On a View

1. Create your own class by extending the View Class
2. Override the onDraw() method

I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box

1. Output Will be like 

2. The Java code is like    MainActivity.java 

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
    ExampleCanvas canvasView;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        canvasView = new ExampleCanvas(this);
        setContentView(canvasView);
    }
    private class ExampleCanvas extends View
    {
        public ExampleCanvas(Context context)
        {
            super(context);
        }

        @Override        protected void onDraw(Canvas canvas)
        {
            super.onDraw(canvas);
            // custom drawing code here            Paint paint = new Paint();
            paint.setColor(Color.RED);
            paint.setTextSize(40);
            paint.setAntiAlias(true);
            canvas.drawColor(Color.WHITE);
            canvas.drawText("Welcome on My Blog",50,60,paint);
            canvas.drawCircle(500, 500, 100, paint);
            canvas.drawRect(150, 150, 250, 300, paint);


        }
    }
}




Sunday, August 14, 2016

Social Integration (FaceBook) in your App- Part I


Hi .... Dear All ....  Today I am uploading a superb example of how Social Integration can be done with you App.
I am integrating the world most popular social site/app @ FaceBook.
In lot of app you have seen on the login page "Login with Facebook " . This functionality is basically used to skip the Registration Procedure so user can enter in your app by using another account like FB.
There are lot of steps please read carefully otherwise you will not reach at your destination.
@  Register yourself as a developer on     https://developers.facebook.com/apps
@ After Registration Add a New App  by clickin on Green Button
@Select Android and Write your App Name go for Create App ID
@ Write your Credentials and Select Options i had selected for Education purpose
@ After Successful generation of App ID  you can goto Quick Start Section or follow my steps .
 Now
1. In your project build.gradle file please add
repositories {
        mavenCentral()
    }
 2. Add compile 'com.facebook.android:facebook-android-sdk:[4,5)' to        
      your build.gradle dependencies.
3. Build Project import package in your Activity as import com.facebook.FacebookSdk;

4. Add in string.xml file as <string name="facebook_app_id">29512.........</string>
5. Add metadata in manifest file in application element as


    ...
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    ...
6. Tell Facebook about your project means package name and Launcher Activity name.
@@@ Don't worry about package name alert dialog if you are not going to upload your App to google play.
7. Generate Hashkey  
7.1    On Mac use the command
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
7.2 On Windows use 

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
***** In most cases people found an openssl error so please first download openssl from 
https://code.google.com/archive/p/openssl-for-windows/downloads
***** Extract zipfile in C drive in your any folder like i created OpenSSL and extract zip  here
Now in command window copy any one command from 7.1 or 7.2 given above and replace 
openssl   by "C:\OpenSSL\bin\openssl.exe"   like for windows as 
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | "C:\OpenSSL\bin\openssl.exe"  sha1 -binary | "C:\OpenSSL\bin\openssl.exe"  base64
******* Insert password android  
***** see your HashgKey copy it and paste onto facebook developer page ... you will get finished message.
********** Congratulations you had integrated FB in your App*****************

In this example you can set alarm after a specified time interval in secs. After your specified time interval your device will vibrate.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box
Now register  FB Activity in your project  manifest file like

<activity android:name="com.facebook.FacebookActivity"

    android:configChanges=

        "keyboard|keyboardHidden|screenLayout|screenSize|orientation"

    android:theme="@android:style/Theme.Translucent.NoTitleBar"

android:label="@string/app_name" />

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

1. Layout File is as
                         


2. XML file is as  with FB Login Button
<?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"

    tools:context="com.exam.ravi.socialintegration.MainActivity"   >

    <com.facebook.login.widget.LoginButton

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/loginFB"

        android:layout_centerVertical="true"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true" />

    <TextView        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="New Text"

        android:id="@+id/textView"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true" />

</RelativeLayout>

3. Java Code is as MainActivity.java

package com.exam.ravi.socialintegration;


import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    LoginButton loginButton;
    CallbackManager callbackManager;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        callbackManager = CallbackManager.Factory.create();
        loginButton = (LoginButton) findViewById(R.id.loginFB);
        textView = (TextView) findViewById(R.id.textView);
        loginButton.registerCallback(callbackManager, 
                   new FacebookCallback<LoginResult>() {
            @Override

            public void onSuccess(LoginResult loginResult) {
            
            textView.setText("User Id= " + loginResult.getAccessToken().getUserId());

            }

            @Override            public void onCancel() {
                Log.v("Ravi", "User Cancelled");
            }

            @Override            public void onError(FacebookException error) {
                Log.v("Ravi", "Something Wrong");
            }
        });
    }
        @Override

   protected void onActivityResult( int req, int res, Intent intnt)
        {
            callbackManager.onActivityResult(req,res,intnt);
        }

}

Multiple Selection in ListView using Contextual Action Bar


Hi .... Dear All ....  Today I am uploading a superb example of how select multiple items in ListView using Contextual Action Bar and take action on selected items. 

The action bar is a dedicated piece of real estate at the top of each screen that is generally persistent throughout the app.
It provides several key functions:
  • Makes important actions prominent and accessible in a predictable way (such as New or Search).
  • Supports consistent navigation and view switching within apps.
  • Reduces clutter by providing an action overflow for rarely used actions.
  • Provides a dedicated space for giving your app an identity.
Contextual Action Bars
  • contextual action bar (CAB) is a temporary action bar that overlays the app's action bar for the duration of a particular sub-task. CABs are most typically used for tasks that involve acting on selected data or text.
From here the user can:
  • Select additional elements by touching them.
  • Trigger an action from the CAB that applies to all selected data items. The CAB then automatically dismisses itself.
  • Dismiss the CAB via the navigation bar's Back button or the CAB's checkmark button. This removes the CAB along with all selection highlights.
  • Use CABs whenever you allow the user to select data via long press. You can control the action content of a CAB in order to insert the actions you would like the user to be able to perform.

In this example you can set alarm after a specified time interval in secs. After your specified time interval your device will vibrate.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box

1. Output Will be like 


2. XML Files 
a. Create a xml file in menu folder 
     i had created context_menu.xml in menu folder which is as 


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

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

    <item        android:id="@+id/delete"

        android:title="Delete Items"

        android:icon="@mipmap/ic_launcher"        />
</menu>

b. activity_main.xml is as 

<?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"

    tools:context="com.exam.ravi.listviewcontextmenu.MainActivity">

    <ListView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/listView"
/>
</RelativeLayout>

3. Java Files is as MainActivity.java 

package com.exam.ravi.listviewcontextmenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    ArrayAdapter<String> adapter;
    ArrayList<String> list = new ArrayList<>();
    ArrayList<String> list_items = new ArrayList<>();
    int count =0;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        list.add("Android");
        list.add("iPhone");
        list.add("Java");
       list.add("Python");
       list.add("Ruby");
       list.add("PHP");
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list); listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener()
{
            @Override

            public void onItemCheckedStateChanged(ActionMode mode, int position,
                                       long id, boolean checked) {
                count++;
                mode.setTitle(count+"Items Selected");
                list_items.add(list.get(position));
            }

            @Override

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);
                return true;
            }

            @Override

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                switch(item.getItemId())
                {
                    case R.id.delete:
                        for(String msg:list_items)
                        {
                            adapter.remove(msg);
                        }
                        Toast.makeText(getBaseContext(),count+"Removed",
                            Toast.LENGTH_LONG).show();
                        count=0;
                        mode.finish();
                        return true;
                    default:
                        return false;
                }

            }

            @Override

            public void onDestroyActionMode(ActionMode mode) {

            }
        });
    }
}