zme*_*eda 7 service android android-activity
做前台服务的正确方法是什么,我以后可以绑定它?我已经关注了Android API演示,其中包含了如何创建前台服务的示例.关于启动服务同时绑定它没有任何示例.
我希望看到音乐播放器服务的一个很好的例子,其活动"绑定"到它.
有没有?
我想做的事情如下:
我必须覆盖哪些方法才能完成此任务?Android的做法是什么?
sil*_*gle 10
在froyo之前,在服务中有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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后为我的媒体播放器更新通知 - 注意前台服务只在媒体播放时需要,并且应该在停止后保持开启,这是一个不好的做法.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
至于绑定 - 你只需要在你的活动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;
}
};
Run Code Online (Sandbox Code Playgroud)
zme*_*eda -6
要完成要求的任务,我唯一要做的就是将以下属性添加到 AndroidManifest.xml 到我的活动定义中
android:launchMode="singleTop"
Run Code Online (Sandbox Code Playgroud)
就是这样。
问候