灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2131回复:0

Android开发——关于Service的一些要点

楼主#
更多 发布于:2012-09-06 14:00

service 有两种调用形式:被启动(startService)和被绑定(bindService)。前者要求在Service类中实现onStartCommand方法,Service启动后需要手动停止,否则永远运行下去;后者要求实现onBind方法,当没有组件绑定到此Service时,它自行了断。
Service需要在manifest文件里声明。通过使用intent-filter可以使得其他程序启动这一Service。
注意!Service在当前application所在的进程中运行,建议自行在Service中创建新线程来执行任务,否则有可能导致application出现“卡”的现象。直接使用 IntentService即可避免这一问题。它甚至已经实现一个任务队列来解决并发的问题。如果确实需要并发的功能则只能自行继承实现Service类了。
onStartCommand()的返回值包括START_NOT_STICKY,START_STICKY,START_REDELIVER_INTENT。详情用力点击相应链接。
如果在用startService启动Service时希望Service返回一个结果,那么可以用 PendingIntent作为参数,利用broadcast获取返回值。


当我们需要与Service进行交互或者希望把部分功能暴露给其他程序的时候,使用bindService。在Service中需实现onBind方法,返回一个IBinder接口,我们需要在此接口中定义一些方法,以便绑定Service的组件能够通过这些方法与Service进行交互。使用unBindService解除绑定。
Service可使用Toast Notifications 或 Status Bar Notifications来通知用户一些信息。


当一个Service的存在是用户能意识到的,如播放器,那么在启动service时使用 startForeground()。样例代码如下:
[java]
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),System.currentTimeMillis());<br />Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);




关于Service的生命周期:
[java]
public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    @Override
    public void onCreate() {
        // The service is being created
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        return mStartMode;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @Override
    public void onRebind(Intent intent) {
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }
    @Override
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }
}


与Activity不同的是,我们再重写时不需要调用这些方法的super实现


最近刚刚使用了Service,感觉关系还是挺混乱的。自己实现的Service类,接口,Listener和Binder,暂时还是觉得没搞透彻,需要继续熟悉一下。




喜欢0 评分0
游客

返回顶部