Unregister BroadcastReceiver which extends a class

喜欢而已 提交于 2019-12-24 19:23:41

问题


I have an class as below:

public class FYPSmsReceiverBroadcast extends BroadcastReceiver

I need to unregister the receiver as I am getting a force close error AFTER I have existed the application when I receive an SMS message. (indicating something is still listening for the sms but not able to access a particular activity because the app has been closed; the error only seems to happen after 1 text received, a second text seems to produce no force close error)

There are a number of somewhat similar questions, but none that can assist the method I have employed. I have tried adding an onPause like below:

 public void onPause() {


        unregisterReceiver(FYPSmsReceiverBroadcast);
    }

But this results in the following error in eclipse: 'FYPReceiverBroadcast cannot be resolved to a variable'

In the onReceive method of the class that extends Broadcast receiver I have a call to: FYPSpeakerActivity.speakSMSfrom();

Which calls another class that uses text to speech - This line appears to be the one being called (despite the application being closed) on receipt of an SMS, and creates the force close error.

Can anyone advise?


回答1:


FYPReceiverBroadcast is a class. You need to pass an object, here is an example:

FYPReceiverBroadcast myFYPReceiverBroadcast = new FYPReceiverBroadcast(...);

...

public void onPause() {
     unregisterReceiver(myFYPReceiverBroadcast);
}

This is such a fundamental programming concept, I recommend you to read the following article to learn the difference:

An object is a software bundle of related state and behavior. A class is a blueprint or prototype from which objects are created.

http://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/



来源:https://stackoverflow.com/questions/11902412/unregister-broadcastreceiver-which-extends-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!