首先编写一个类继承Service这个基类,重写里面的方法,然后在Activity中调用startService()和stopService()来启动和停止服务
package com.service.activity;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class ExampleService extends Service{
private static final String TAG = "ExampleService";
@Override
public void onCreate() {
Log.i(TAG, "ExampleService-onCreate");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i(TAG, "ExampleService-onStart");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//执行文件的下载或者播放等操作
Log.i(TAG, "ExampleService-onStartCommand");
/*
* 这里返回状态有三个值,分别是:
* 1、START_STICKY:当服务进程在运行时被杀死,系统将会把它置为started状态,但是不保存其传递的Intent对象,之后,系统会尝试重新创建服务;
* 2、START_NOT_STICKY:当服务进程在运行时被杀死,并且没有新的Intent对象传递过来的话,系统将会把它置为started状态,
* 但是系统不会重新创建服务,直到startService(Intent intent)方法再次被调用;
* 3、START_REDELIVER_INTENT:当服务进程在运行时被杀死,它将会在隔一段时间后自动创建,并且最后一个传递的Intent对象将会再次传递过来。
*/
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "ExampleService-onBind");
return null;
}
@Override
public void onDestroy() {
Log.i(TAG, "ExampleService-onDestroy");
super.onDestroy();
}
}
MainActivity.java
[html]
package com.service.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private static final String TAG = "MainActivity"; //日志输出标志
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(this);
btnStopService.setOnClickListener(this);
}
//点击事件处理监听器
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ExampleService.class);
switch(v.getId()){
case R.id.btnStartService:
startService(intent);
break;
case R.id.btnStopService:
stopService(intent);
break;
default:
break;
}
}
}