在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);
}
}
关于绑定(bind) - 在您的活动(activity) onStart 方法中,您只需像绑定到任何服务(service)一样进行绑定(bindService)调用即可(无论它是否在前台)。
MediaPlayerService mpService=null;
@Override
protected void onEWCreate(Bundle savedInstanceState) {
Intent intent = new Intent(this, MediaPlayerService.class);
startService(intent);
}
@Override
protected void onStart() {
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;
}
};