Started
startService():调用者和服务之间没有联系,即使调用者退出了,服务仍然进行 [onCreate()-->startService()-onDestory()]
Bound
bindService():调用者和服务绑在一起,调用者一旦退出服务也就终止[onCreate()-->onBind()-->onUnbind()-->onDestory()]
startService()
public class MainActivity extends Activity
{
private Button btnStartService;
private Button btnStopService;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStartService = (Button) findViewById(R.id.btnStartService);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStartService.setOnClickListener(listener);
btnStopService.setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent=new Intent(MainActivity.this, ExampleService.class);//用intent调用
switch (v.getId())
{
case R.id.btnStartService:
startService(intent); //开始service
break;
case R.id.btnStopService:
stopService(intent);//结束service
break;
default:
break;
}
}
};
}
public class ExampleServices extends Service { //继承service
private static final String TAG="ExampleServices";
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Log.i(TAG,"ExampleServices-->onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"ExampleServices-->onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(TAG,"ExampleServices-->onDestroy");
super.onDestroy();
}
}
AndroidManifest.xml文件里要配置service:`
<service android:name=".ExampleService" />
三个常量:
START_STICKY:当服务进行在运行时被杀死,系统将会把它值为started状态,但是并不保存其传递的Intent对象
START_NOT_STICKY:当服务进行在运行时被杀死,并且没有新的Intent对象传递过来,统将会把它值为started状态,但是并不会再次创建进程,直到startService(Intent)方法被调用。
START_REDELIVER_INTENT:当服务进行在运行时被杀死,它将会间隔一段时间后重新被创建,并且最后一个传递的Intent对象将会再次传递过来。
什么时候使用service?
执行一个耗时的操作,但不要和用户交互,比如下载东西,下载的过程不用和用户交互
什么时候使用thread?
如果用户需要和应用程序交互时。比如有一种播放音乐器,和用户的交互相关,当用户一段时间不操作时,播发器机会自动退出,这样就要新建一个线程