问题
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