Service
- A Service is an application component that can perform long-running
- Another application component can start a service and it will continue to
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
- Heavy code is not done in service.
- A service is "started" when an application component (such as an
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:
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:
Declaring a service in the manifest:
application's manifest file.
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>
- onStartCommand (Intent intent, int flags, int startId) You should not
- Instead, override onHandleIntent(Intent), which the system calls when the
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
- Clients send requests throughstartService(Intent) calls; the service is
- itself when it runs out of work.
- Creates a work queue that passes one intent at a time toyour
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.