Activity: it is single screen application. it is a foreground process.it contain user interaction.
Service:
a service is a component which runs in the background without interacting with user.
Android provides many predefined services exposed via Manager class.
Own services must be declared in the manifest file..
Some methods:
An activity can start a service via startService() method.
stop the service by using stopService() method.
bindService() - this is for activity to interact with service.
it needs "ServiceConnection" object.
Once service is started onCreate() is called.
onStart()
onBind()- the system calls when other component want to bind the service.
onStop() - for stopping the service.
OnDestroy()- called when service is no longer used. and it is destroyed.
ex:
MainActivity.java
package
com.example.serviceexample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
implements OnClickListener {
Button b1;
Button b2;
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu);
return true;
}
public void
onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
startService(new Intent(this,ServiceDemo.class));
break;
case R.id.button2:
startService(new Intent(this,ServiceDemo.class));
}
}
}
ServiceDemo.java
package com.example.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class
ServiceDemo extends Service{
MediaPlayer mediaplayer;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method
stub
return null;
}
@Override
public void
onCreate() {
// TODO Auto-generated method
stub
super.onCreate();
mediaplayer=MediaPlayer.create(this,
R.raw.newsong);
}
@Override
public void
onDestroy() {
// TODO Auto-generated method
stub
super.onDestroy();
mediaplayer.stop();
}
@Override
public void
onStart(Intent intent, int
startId) {
// TODO Auto-generated method
stub
super.onStart(intent, startId);
mediaplayer.start();
}
}
Declare
manifest permission for service
<service
android:name="ServiceDemo"></service>
you can download source code here
http://www.4shared.com/rar/O39SukJ_/ServiceExample.html?
you can download source code here
http://www.4shared.com/rar/O39SukJ_/ServiceExample.html?
0 coment�rios:
Post a Comment