关于Activity的生命周期

时间:2013-09-05 09:20:36

标签: android android-activity

public class MyReceiver extends BroadcastReceiver {
private static IReceiveMessage iReceiveMessage;
@Override
public void onReceive(Context context, Intent intent) {
       iReceiveMessage.receiveMessage(intent.getStringExtra("message"));
}       
public static void setReceiveMessage(IReceiveMessage iReceiveMessage1) {
    iReceiveMessage = iReceiveMessage1;
}}

public interface IReceiveMessage {
public void receiveMessage(String message);
}




public class MainActivity extends Activity implements IReceiveMessage{

    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              MyReceiver.setReceiveMessage(this);

}
     @Override
public void onReceiverMessage(String message) {
Log.i("test", message);

}
}

为什么Mainactivity在退出后仍会收到来自MyReciever的消息?

1 个答案:

答案 0 :(得分:1)

您需要在onDestroy()中取消注册您的活动:

protected void onDestroy() {
      super.onDestroy();
      MyReceiver.setReceiveMessage(null);
}