服务是在后台(在UI线程上)运行而无需与用户直接交互的组件。一个未绑定的服务刚刚启动,并且未绑定到任何Activity的生命周期。
要启动服务,您可以按照以下示例所示进行操作:
// 该意图将用于启动服务
Intent i= new Intent(context, ServiceName.class);
// 可能将数据添加到意图附加中
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);您可以通过onStartCommand()覆盖使用意图中的任何其他功能:
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent != null) {
Bundle extras = intent.getExtras();
String key1 = extras.getString("KEY1", "");
if (key1.equals("Value to be used by the service")) {
//做点什么
}
}
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}