前台服务的正确方法是什么,我以后可以绑定它? 我已经关注了Android API演示,其中包含了如何创建前台服务的示例。 关于启动服务同时绑定它没有任何示例。
我希望看到音乐播放器服务的一个很好的例子,活动“绑定”它。
有没有?
我想做类似的事情:
我必须覆盖哪些方法才能完成此任务? Android的这种做法是什么?
答案 0 :(得分:10)
现在有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"
就是这样。
此致