Intent serviceIntent = new Intent(this, MyService.class); startService(serviceIntent);
Intent serviceIntent = new Intent(this, MyService.class); serviceIntent.putExtra("key", "value"); startService(serviceIntent);
public class MyService extends Service { @Override public void onCreate() { // 服务创建时执行的代码 super.onCreate(); }
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 服务启动时执行的代码
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// 返回IBinder对象
return null;
}
}
注:在Android O以后的版本中,启动服务的方式有所不同。需要在服务中调用startForeground()方法并传入Notification对象。