升级Froyo之前有setForeground(真)的服务,这是很容易,但也容易被滥用。
需要通知现在有startForeGround服务被激活(使用户可以看到有一个foregroundservice运行)。
我做了这个类来控制它:
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;
}
};
什么是“onEWCreate”,是你的手写错误或我的小知识? – pengwang 2011-03-23 05:41:00
oppps对不起,它显示onCreate - 这是我自己的异常报告封装。 – siliconeagle 2011-03-23 21:12:56
我发现了API Demos演示的奇怪行为。如果您转到API演示(API版本7)并转到应用程序 - >服务 - >本地服务控制器,点击启动服务。现在通知在notif。酒吧正在运行。现在按HOME按钮,并通知。栏并按下服务通知(Sample Local Service)。现在!你必须按回三次才能返回。为什么在世界上?!!? – zmeda 2011-04-04 19:49:32