Thursday 17 March 2016

Bind Service

                                     Bind Service



Method for starting the bind service:
BindService(intent,service connection,flags);

Method for disconnect the bind service:

UnbindService(Service connected);

Implement ServiceConnection:

Your implementation must override two callback methods:
onServiceConnected()

  •  The system calls this to deliver the IBinder returned by the service's

onServiceDisconnected()

  • The Android system calls this when the connection to the service is 
        unexpectedly lost, such as when the service has crashed or has been killed. This is not called when the client unbinds.


Lifecycle for Bind Service:



  • A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it.
  • To provide binding for a service, you must implement the onBind()callback method.
  • This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.


Example program :

It is a xml file:

<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:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="bindservice"

      android:onClick="bind"

        android:id="@+id/button"

        android:layout_centerVertical="true"

        android:layout_centerHorizontal="true" />

</RelativeLayout>

In MainActivity we call the serice :

public class MainActivity extends AppCompatActivity implements

ServiceConnection {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

    @Override

    public void onServiceConnected(ComponentName name, IBinder

service) {

        MyService.MyBinder myBinder = (MyService.MyBinder)service;

        MyService s = (MyService)myBinder.getService();

        Toast.makeText(MainActivity.this,"service

connected"+s.getvalue(),Toast.LENGTH_LONG).show();

    }

    @Override

    public void onServiceDisconnected(ComponentName name) {

    }

    public void bind(View v){

        Intent intent=new Intent(MainActivity.this,MyService.class);

        bindService(intent,MainActivity.this,BIND_AUTO_CREATE);

    }

}

It is a Service:

public class MyService extends Service {

    private int a = 10;

    public MyService() {

    }

    public IBinder mBinder = new MyBinder();

    class MyBinder extends Binder {

        MyService getService() {

            return MyService.this;

        }

    }

    @Override

    public IBinder onBind(Intent intent) {

        return mBinder;

    }

    public int getvalue() {

return a;

    }

    @Override

    public boolean onUnbind(Intent intent) {

        return true;

    }

    @Override

    public void onRebind(Intent intent) {

        super.onRebind(intent);

    }

}




Please share your feedback about this topic.

Thursday 11 February 2016

Android Services

 Service



  • A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.


  • Another application component can start a service and it will continue to
run in the background even if the user switches to another application.


 For example,

play music, perform file I/O, or interact with a content provider, all from the background.

Types of Services:

It is classified into three types,

Started Service: 


Lifecycle for services

        

  • In Started Service the data cannot get back to the Activity.
  • Only do start the background process indefinitely, even if the component
         that started it is destroyed.
  • Heavy code is not done in service. 

  • A service is "started" when an application component (such as an
       activity) starts it by calling StartService().

For example,

Intent intent=new Intent(Context,Class);

startService(Intent);

  • If a component starts the service by calling startService().

Stop the Services by two methods:

  • The service remains running until it stops itself with stopSelf() .
  • The component stops it by callingstopService().

Methods:

  •  onStartCommand (Intent intent, int flags, int startId) You should not 
         override this method for your IntentService.
  • Instead, override onHandleIntent(Intent), which the system calls when the 
 IntentService receives a start request.
Parameters

intent                   The Intent supplied to startService(Intent), as given. This
                              may be null if the service is being restarted after its
                              process has gone away, and it had previously returned
                              anything except

flags                     Additional data about this start request. Currently either
                             0, START_FLAG_REDELIVERY,

startId                 A unique integer representing this specific request to
                             start. Use with

Intent Service:

Lifecycle for Intent Service:



  • It is a child class of Started Service that handle asynchronous requests
        (expressed as Intents) on demand.
  • Clients send requests throughstartService(Intent) calls; the service is
       started as needed, handles each Intent in turn using a worker thread, and      stops
  • itself when it runs out of work.
  • Creates a work queue that passes one intent at a time toyour 
     onHandleIntent() implementation, so you never have to worry about     multi-threading.

Declaring a service in the manifest:

  • Like activities (and other components), you must declare all services in your

application's manifest file.

  • To declare your service, add a <service> element as a child of

the <application> element. For example:

<manifest …>



<application …>

<service

    android:name=".MyService"

    android:enabled="true"

    android:exported="true"/ >

</application>

</manifest>

Example program :

It is a xml file:

<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:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="click"

        android:onClick="download"

        android:id="@+id/button"

        android:layout_centerVertical="true"

        android:layout_alignParentStart="true" />

  

</RelativeLayout>

In MainActivity we call the serice :

public class MainActivity extends AppCompatActivity {

Button click;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        click=(Button)findViewById(R.id.button);

    }

    public void download(View v){

        Intent intent=new Intent(MainActivity.this,MyService.class);

        startService(intent);

    }

}

In Service extends the Spanner thread:

public class MyService extends Service {

    public MyService() {

    }

    @Override

    public IBinder onBind(Intent intent) {

        // TODO: Return the communication channel to the service.

        throw new UnsupportedOperationException("Not yet

implemented");

    }

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        new Asyntask().execute(" ");

        return super.onStartCommand(intent, flags, startId);

    }

}

It is a Spanner Thread:

public class Asyntask extends AsyncTask<String,String,Bitmap> {

    Bitmap b=null;

    @Override

    protected void onPreExecute() {

        super.onPreExecute();

    }

    @Override

    protected Bitmap doInBackground(String... params) {

        try {

            b=BitmapFactory.decodeStream((InputStream) new

URL(params[0]).getContent());

        } catch (IOException e) {

            e.printStackTrace();

        }

        return b;

    }

    @Override

    protected void onPostExecute(Bitmap bitmap) {

        super.onPostExecute(bitmap);

        try {

            File f = new

File(Environment.getExternalStoragePublicDirectory(Environment.DIRECT

ORY_DOWNLOADS), "hai.png");

            if (!f.exists()) {

                f.createNewFile();

            }

            FileOutputStream fos = new FileOutputStream(f);

            b.compress(Bitmap.CompressFormat.PNG, 90, fos);

            fos.flush();

            fos.close();

        }catch (Exception e){

        }

    }

}

In Manifest:

<manifest …>

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

<uses-permission

android:name="android.permission.WRITE_EXTERNAL_STORAGE"/

>



<application …>

<service

    android:name=".MyService"

    android:enabled="true"

    android:exported="true"/ >

</application>

</manifest>



Please share your feedback about this topic.

Sunday 7 February 2016

Java Interface

Interface

What is interface:

  • Interface is similar to class.it is a collection of abstract method.
  • Interface dont have defination.
  • A class can implements an interface.thereby inheriting a abstract methods of the interface.
  • Abstract methods an interface also contain constants,and default methods,static methods.
  • Method body exits only for default methods and static methods.
  • Interface can have any number of methods.
  • You cant create object for interface.
  • Interface dont not have constractor.
  • An interface can extend multiple interfaces.

Declaring Interfaces: 

  • The interface keyword is used to declare an interface.

    Example:

    public interface SampleInterface{

}

properties for interface:
  • An interface is a implictily abstract menthod so you no need to declare abstract keyword.
  • Methods in an interface are implicitily public.
Example:

interface Animal{

public void eat();

public void travel();

}

Implemeting Interface:

  • A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
Example:

public class Mammal implements Animal{

public void eat(){

System.out.println("Mammal can eat");

}
public void travel(){

System.out.println("Mammal can travel");

}
public int noOfLegs(){

return 0;

}

Public static void main(String args[]){

Mammal mam=new Mammal();

mam.eat();

mam.travel();

}

}

Result:

Mammal can eat.
Mammal can travel.



Please share your feedback about this topic.