如何在Android中的Service Class中实现BroadcastReceiver?

前端之家收集整理的这篇文章主要介绍了如何在Android中的Service Class中实现BroadcastReceiver?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在我创建的Service类中实现BroadcastReceiver:
public class MyService extends Service

在这个类中,当用户按下实现sendBroadcas()的MyActivity类中的按钮时,我必须通过使用Thread – Sleep来实现下载模拟.我不能将Service类扩展为BroadcastReceiver,因为它已经扩展到Service.任何人都可以帮我弄清楚如何实现这一机制?

谢谢

解决方法

将BroadcastReceiver作为顶级类或作为服​​务中的内部类.并在您的服务中获得接收器的参考.喜欢这个:
public class MyService extends Service {
    BroadcastReceiver mReceiver;

    // use this as an inner class like here or as a top-level class
    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context,Intent intent) {
            // do something
        }

        // constructor
        public MyReceiver(){

        }
    }

    @Override
    public void onCreate() {
         // get an instance of the receiver in your service
         IntentFilter filter = new IntentFilter();
         filter.addAction("action");
         filter.addAction("anotherAction");
         mReceiver = new MyReceiver();
         registerReceiver(mReceiver,filter);
    }
}

猜你在找的Android相关文章