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.

0 comments:

Post a Comment