2014-01-15 35 views
0

我已經對在MainActivity類的樣帶碼 -Android的 - 未註冊的接收器logcat的錯誤

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     // Setting a receiver - to know if the user is charging his mobile 
     receiverAcDc = new ChargingReciver(); 
     IntentFilter filterAcDc = new IntentFilter(); 
     filterAcDc.addAction(Intent.ACTION_POWER_CONNECTED); 
     filterAcDc.addAction(Intent.ACTION_POWER_DISCONNECTED); 
     registerReceiver(receiverAcDc, filterAcDc); 

} 

現在我還添加在MainActivity下一個代碼 -

@Override 
    protected void onPause() { 
     super.onPause(); 


    // Trying to closing the receivers when the user leaving the activity 
    try { 

     unregisterReceiver(sea); 
     unregisterReceiver(receiverAcDc); 

    } catch (RuntimeException e) { 
     e.printStackTrace(); 
    } 

    } 

現在的事是 - 當我離開應用程序時(例如按回來) - 我得到下一個logcat錯誤 -

01-15 15:05:46.421: E/ActivityThread(2639): Activity com.example.myplaces1.view.MainActivity has leaked IntentReceiver [email protected] that was originally registered here. Are you missing a call to unregisterReceiver()? 

所以我應該怎麼做才能避免這個logcat錯誤? 感謝任何形式的幫助

,讓我錯誤的接收器是在不同的類,這是它的代碼 -

public class ChargingReciver extends BroadcastReceiver{ 


    @Override 
    public void onReceive(Context context, Intent intent) { 

     String reciveAction = intent.getAction(); 

     // If the device is connected to a power supply 
     if (Intent.ACTION_POWER_CONNECTED.equals(reciveAction)) { 
      // Notify the user the device is being charged 
      Toast.makeText(context, R.string.charging, Toast.LENGTH_SHORT) 
        .show(); 
     } else { 
      // Notify the user the device is disconnected from power supply 
      Toast.makeText(context, R.string.charging_no, Toast.LENGTH_SHORT) 
        .show(); 
     } 
    } 

    } 

回答

0

當您註冊以這種方式接收器,它的生命如 長因爲組件處於活動狀態,並且Android將事件發送到此接收器的 ,直到創建組件本身獲得 銷燬。

正確處理生命週期是您的任務。因此,當你動態地添加一個接收者時,注意在你的Activity的onPause()方法中註銷同一個接收者!我建議在你的Activity的onResume()方法中註冊接收者,並在你的onPause()方法。

+0

嗯,我厭倦了清單的事情 - 仍然得到了logcat錯誤。我也厭倦了在onResume()中註冊接收器,並在onPause()註銷它 - 但仍然存在相同的logcat錯誤 – 4this