可以绑定的Android前台服务

时间:2011-03-21 20:34:01

标签: android service android-activity

前台服务的正确方法是什么,我以后可以绑定它? 我已经关注了Android API演示,其中包含了如何创建前台服务的示例。 关于启动服务同时绑定它没有任何示例。

我希望看到音乐播放器服务的一个很好的例子,活动“绑定”它。

有没有?

我想做类似的事情:

  • 当程序第一次出现时(首先意味着服务尚未启动),我想启动前台服务,完成所有工作。用户界面(活动)就是控制该工作
  • 如果用户按下主页按钮服务必须保持正常运行(并且必须存在栏中的通知)
  • 现在,如果用户点击通知栏活动中的通知应该开始并绑定到服务(或类似的方式,正确的方式),并且用户可以控制该作业。
  • 如果活动处于活动状态且用户按下按钮,则应销毁活动,并且还应销毁服务。

我必须覆盖哪些方法才能完成此任务? Android的这种做法是什么?

2 个答案:

答案 0 :(得分:10)

在froyo之前,在Service中有setForeground(true)这很容易,但也容易被滥用。

现在有startForeGround服务需要激活通知(因此用户可以看到有一个前台服务正在运行)。

我让这个班来控制它:

public class NotificationUpdater {
    public static void turnOnForeground(Service srv,int notifID,NotificationManager mNotificationManager,Notification notif) {
        try {
            Method m = Service.class.getMethod("startForeground", new Class[] {int.class, Notification.class});
            m.invoke(srv, notifID, notif);
        } catch (Exception e) {
            srv.setForeground(true);
            mNotificationManager.notify(notifID, notif);
        }
    } 

    public static void turnOffForeground(Service srv,int notifID,NotificationManager mNotificationManager) {
        try {
            Method m = Service.class.getMethod("stopForeground", new Class[] {boolean.class});
            m.invoke(srv, true);
        } catch (Exception e) {
            srv.setForeground(false);
            mNotificationManager.cancel(notifID);
        }
    }
}

然后为我的媒体播放器更新通知 - 请注意,只有在播放媒体时才需要前台服务,并且应该在播放后停止播放,这是一种不好的做法。

private void updateNotification(){
    boolean playing = ((mFGPlayerBean.getState()==MediaPlayerWrapper.STATE_PLAYING) || 
                        (mBGPlayerBean.getState()==MediaPlayerWrapper.STATE_PLAYING));
    if (playing) {
        Notification notification = getNotification();
        NotificationUpdater.turnOnForeground(this,Globals.NOTIFICATION_ID_MP,mNotificationManager,notification);
    } else {
        NotificationUpdater.turnOffForeground(this,Globals.NOTIFICATION_ID_MP,mNotificationManager);
    }
}

至于绑定 - 您只需在活动onStart中以正常方式绑定您只需进行bindService调用,因为您将绑定到任何服务(无论天气是否与前景无关)

MediaPlayerService mpService=null;
@Override
protected void onEWCreate(Bundle savedInstanceState) {
     Intent intent = new Intent(this, MediaPlayerService.class);
     startService(intent);
}

@Override
protected void onStart() {
    // assume startService has been called already
    if (mpService==null) {
        Intent intentBind = new Intent(this, MediaPlayerService.class);
        bindService(intentBind, mConnection, 0);
    }
}

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mpService = ((MediaPlayerService.MediaBinder)service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        mpService = null;
    }
};

答案 1 :(得分:-3)

要完成被询问的任务,我唯一需要做的就是将以下属性添加到AndroidManifest.xml到我的活动定义

android:launchMode="singleTop"

就是这样。

此致