在活动打开时启动服务

时间:2015-12-21 21:49:09

标签: android android-service

如何在打开活动时启动服务,我正在使用意图,但服务根本没有启动。音乐打算在打开某个页面时播放,但根本没有服务正在运行。

这是我用来在MainPage类上启动服务的代码。

public class BackgroundMusic extends Service implements Application.ActivityLifecycleCallbacks, Runnable {

MediaPlayer player;

private static final Handler uiHandler = new Handler(Looper.getMainLooper());

@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.backgroundmusic);
    player.setLooping(true);
    player.setVolume(100, 100);
    player.start();
    Intent BackgrndMusic = new Intent(this, MainPage.class);
    startService(BackgrndMusic);
    getApplication().registerActivityLifecycleCallbacks(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    // stop listening for activities
    getApplication().unregisterActivityLifecycleCallbacks(this);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onActivityStarted(Activity activity) {
    // do not destroy this service
    uiHandler.removeCallbacks(this);
}

@Override
public void onActivityStopped(Activity activity) {
    // if an activity don't show up in 1 second, destroy this service
    uiHandler.postDelayed(this, 1000);
}

@Override
public void run() {
    // no more activity, destroy this service
    stopSelf();
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
    startService(BackgrndMusic);
}

@Override
public void onActivityResumed(Activity activity) {
    Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
    startService(BackgrndMusic);
}

@Override
public void onActivityPaused(Activity activity) {
    Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
    stopService(BackgrndMusic);
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {
    Intent BackgrndMusic = new Intent(BackgroundMusic.this, MainPage.class);
    stopService(BackgrndMusic);
}

}

1 个答案:

答案 0 :(得分:1)

使用

@Override
protected void onResume()
{
super.onResume();
startService(foo);
}

@Override
protected void onDestroy()
{
 super.onDestroy();
 StopService(foo);
}