2015-11-03 65 views
0

這個問題之前已被多次詢問過,而且沒有任何一個人的答案能解決我的問題。我嘗試了通過按下按鈕,進入onPause和onDestroy來取消註冊聽衆的每種方法;但即使應用程序關閉,監聽器仍然存在。更重要的是,我敬酒我的偵聽器正在填充的數組的大小,即使應用程序已關閉,Toast仍會繼續增加。我嘗試過使用null和LISTEN_NONE以及我可以在網上找到的所有其他內容。PhoneStateListener不會發布,也沒有以前發佈的答案已經工作

// Name of this file is Second.class 
public class Second extends Activity { 

    SignalStrengthListener signalStrengthListener; 
    TextView lteRsrp; 
    TextView lteRsrq; 
    TextView cellPciTextView; 
    TextView timerValue; 
    Button startButton, stopButton; 

    TelephonyManager tm; 
    List<CellInfo> cellInfoList; 
    String lte1, lte2; 
    int cellPci = 0; 
    long startTime = 0L; 
    long timeInMilliseconds = 0L; 
    long timeSwapBuff = 0L; 
    long updatedTime = 0L; 
    ArrayList<String> rsrpArray; 
    ArrayList<String> rsrqArray; 
    ArrayList<String> pciArray; 


    Handler customHandler = new Handler(); 
    boolean flag = true; 

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

     flag = false; 

     rsrpArray = new ArrayList<>(); 
     rsrqArray = new ArrayList<>(); 
     pciArray = new ArrayList<>(); 

     lteRsrp = (TextView) findViewById(R.id.lteRsrp); 
     lteRsrq = (TextView) findViewById(R.id.lteRsrq); 
     cellPciTextView = (TextView) findViewById(R.id.cellPciTextView); 
     timerValue = (TextView) findViewById(R.id.timerValue); 
     startButton = (Button) findViewById(R.id.startButton); 
     stopButton = (Button) findViewById(R.id.stopButton); 



     startButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startTime = SystemClock.uptimeMillis(); 
       customHandler.postDelayed(updateTimerThread, 0); 

       //start the signal strength listener 
       signalStrengthListener = new SignalStrengthListener(); 

       ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS); 
       tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

       try { 
        cellInfoList = tm.getAllCellInfo(); 
       } catch (Exception e) { 
        Log.d("SignalStrength", "+++++++++++++++++++++++++++++++++++++++++ null array spot 1: " + e); 

       } 


       try { 
        for (CellInfo cellInfo : cellInfoList) { 
         if (cellInfo instanceof CellInfoLte) { 
          // cast to CellInfoLte and call all the CellInfoLte methods you need 
          // Gets the LTE PCI: (returns Physical Cell Id 0..503, Integer.MAX_VALUE if unknown) 
          cellPci = ((CellInfoLte) cellInfo).getCellIdentity().getPci(); 
         } 
        } 
       } catch (Exception e) { 
        Log.d("SignalStrength", "++++++++++++++++++++++ null array spot 2: " + e); 
       } 

      } 
     }); 

     stopButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       timeSwapBuff += timeInMilliseconds; 
       customHandler.removeCallbacks(updateTimerThread); 
       flag = true; 

       try{ 
        if(signalStrengthListener != null) { 
         tm.listen(signalStrengthListener, SignalStrengthListener.LISTEN_NONE); 
         Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Success!!!!!!"); 
        } 
       }catch(Exception e){ 
        e.printStackTrace(); 
        Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Fail!!!!!! with error = " + e); 
       } 
      } 
     }); 


    } 

    private Runnable updateTimerThread = new Runnable() { 
     public void run() { 
      timeInMilliseconds = SystemClock.uptimeMillis() - startTime; 
      updatedTime = timeSwapBuff + timeInMilliseconds; 
      int secs = (int) (updatedTime/1000); 
      int mins = secs/60; 
      secs = secs % 60; 
      int milliseconds = (int) (updatedTime % 1000); 
      timerValue.setText("" + mins + ":" 
       + String.format("%02d", secs) + ":" 
       + String.format("%03d", milliseconds)); 
      customHandler.postDelayed(this, 0); 
     } 
    }; 


    private class SignalStrengthListener extends PhoneStateListener { 
     @Override 
     public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) { 

      //++++++++++++++++++++++++++++++++++ 

      ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener, SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS); 

      tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

      String ltestr = signalStrength.toString(); 
      String[] parts = ltestr.split(" "); 
      lte1 = parts[9]; 
      lte2 = parts[10]; 

      try { 
       cellInfoList = tm.getAllCellInfo(); 
       for (CellInfo cellInfo : cellInfoList) { 
        if (cellInfo instanceof CellInfoLte) { 
         // cast to CellInfoLte and call all the CellInfoLte methods you need 
         // Gets the LTE PCI: (returns Physical Cell Id 0..503, Integer.MAX_VALUE if unknown) 
         cellPci = ((CellInfoLte) cellInfo).getCellIdentity().getPci(); 
        } 
       } 
      } catch (Exception e) { 
       Log.d("SignalStrength", "+++++++++++++++++++++++++++++++ null array spot 3: " + e); 
      } 

      if (!flag) { 
       rsrpArray.add(lte1); 
       rsrqArray.add(lte2); 
       pciArray.add(Integer.toString(cellPci)); 
       int size = rsrpArray.size(); 
       Toast.makeText(Second.this, "Array size = " + size, Toast.LENGTH_LONG).show(); 
      } 

      lteRsrp.setText(String.valueOf(lte1)); 
      lteRsrq.setText(String.valueOf(lte2)); 
      cellPciTextView.setText(String.valueOf(cellPci)); 

      super.onSignalStrengthsChanged(signalStrength); 

      //++++++++++++++++++++++++++++++++++++ 

     } 
    } 



    @Override 
    public void onPause() { 
     Log.d("onPause SigStr", "+++++++++++++++++++++++++++++++++++ onPause"); 
     try{ 
      if(signalStrengthListener != null){ 
       tm.listen(signalStrengthListener, SignalStrengthListener.LISTEN_NONE); 
       Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Success!!!!!!"); 
      } 
     }catch(Exception e){ 
      e.printStackTrace(); 
      Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Fail!!!!!! with error = " + e); 
     } 
     flag = true; 
     super.onPause(); 

    } 

    @Override 
    public void onDestroy() { 

     Log.d("onPause SigStr", "+++++++++++++++++++++++++++++++++++ onDestroy"); 
     try{ 
      if(signalStrengthListener != null) { 
       tm.listen(signalStrengthListener, SignalStrengthListener.LISTEN_NONE); 
       Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Success!!!!!!"); 
      } 
     }catch(Exception e){ 
      e.printStackTrace(); 
      Log.d("TAG", "+++++++++++++++++++++++++++++++++++ Fail!!!!!! with error = " + e); 
     } 
     flag = true; 
     super.onDestroy(); 

    } 
} 

我的代碼開始變得醜陋和多餘的,因爲我一直在清理東西,希望它可以註銷我的聽衆。以下是Second.class的XML佈局。在XML佈局文件的名稱是second_activity.xml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#42abc0"> 

    <TextView 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:text="" 
     android:textSize="16sp" 
     android:textColor="#000000" 
     android:id="@+id/lteRsrp" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginStart="29dp" 
     android:layout_marginTop="31dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="= LTE RSRP" 
     android:textSize="16sp" 
     android:textColor="#000000" 
     android:id="@+id/textView2" 
     android:layout_alignTop="@+id/lteRsrp" 
     android:layout_centerHorizontal="true" /> 

    <TextView 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:text="" 
     android:textColor="#000000" 
     android:textSize="16sp" 
     android:id="@+id/lteRsrq" 
     android:layout_below="@+id/lteRsrp" 
     android:layout_alignStart="@+id/lteRsrp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="= LTE RSRQ" 
     android:textSize="16sp" 
     android:textColor="#000000" 
     android:id="@+id/textView3" 
     android:layout_below="@+id/textView2" 
     android:layout_alignStart="@+id/textView2" /> 

    <TextView 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:text="" 
     android:textSize="16sp" 
     android:textColor="#000000" 
     android:id="@+id/cellPciTextView" 
     android:layout_below="@+id/lteRsrq" 
     android:layout_alignStart="@+id/lteRsrq" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="= LTE PCI" 
     android:textSize="16sp" 
     android:textColor="#000000" 
     android:id="@+id/textView4" 
     android:layout_below="@+id/textView3" 
     android:layout_alignStart="@+id/textView3" /> 

    <Button 
     android:layout_width="120dp" 
     android:layout_height="wrap_content" 
     android:text="Start" 
     android:textColor="#000000" 
     android:textSize="22sp" 
     android:id="@+id/startButton" 
     android:layout_alignParentBottom="true" 
     android:layout_toEndOf="@+id/textView3" 
     android:layout_marginBottom="48dp" 
     android:background="#ffffff" 
     android:textAlignment="center" 
     android:textStyle="bold" 
     android:padding="4dp" /> 

    <Button 
     android:layout_width="120dp" 
     android:layout_height="wrap_content" 
     android:text="Stop" 
     android:textSize="22sp" 
     android:textColor="#000000" 
     android:id="@+id/stopButton" 
     android:layout_alignBottom="@+id/startButton" 
     android:layout_alignStart="@+id/cellPciTextView" 
     android:background="#ffffff" 
     android:textStyle="bold" 
     android:padding="4dp" 
     android:textAlignment="center" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/timerVal" 
     android:textSize="40sp" 
     android:textColor="#000000" 
     android:id="@+id/timerValue" 
     android:layout_above="@+id/startButton" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="55dp" /> 


</RelativeLayout> 

而以下是我的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.parksjg.its.pscrindoortesttool" > 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" > 
     <activity android:name=".First" 
      android:screenOrientation="portrait" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity android:name=".Second" 
      android:screenOrientation="portrait"> 

     </activity> 
    </application> 

</manifest> 

同樣,這個問題已經被問過,但沒有公佈答案的工作! !這裏有幾個,並注意沒有一個答案是上投或它從來沒有被標記爲已經工作: Android : why PhoneCallListener still alive after activity finish?

Android : how to stop listening a PhoneCallListener?

希望我可以俯瞰簡單的東西,有人能指出。讓我知道你是否需要更多的代碼,或者想讓我在GitHub上發佈整個Android Studio項目。

謝謝!

+0

我還沒有測試過,但所有我可以建議你創建全局靜態布爾變量,並在onCreate()應用程序運行時標記爲true,並在ondestroy或onpause下標記爲false。並且在你的監聽器中,如果(IsApplicationRunning){//做其他事情} else {//忽略它},那麼即使你的應用程序與系統掛鉤,儘管沒有被使用,至少它會查找這種情況跑。 – dawncode

+0

這是我最近一直在嘗試,但沒有成功。如果你看看上面的代碼,那就是'布爾標誌',我試圖把它放在許多不同的地方。例如,在上面的代碼中,我將onPause方法中的標誌設置爲true,這應該防止偵聽器繼續執行,但它只是繼續前進。我還使用'flag'布爾將所有代碼包含在SignalStrengthListener中的if語句中。 – JParks

+0

我也有onPause和onDestroy中的調試註釋,它們總是打印成功註釋,所以我知道在'flag'bool被重新分配之前,偵聽器已經設置爲LISTEN_NONE。如果你看到更符合邏輯的方式來使用'flag'布爾值,請告訴我。謝謝你的時間。 – JParks

回答

0

我想我想清楚發生了什麼。我在代碼中添加了更多的Log.d()語句,以確定SignalStrengthListener被調用的次數。我跑了3秒鐘的應用程序,發現SignalStrengthListener被調用了大約300次!比我想象的要多得多。現在問題在於Toast無法跟上它被調用的次數。所以當我停止或關閉應用程序時,敬酒會持續幾分鐘後出現。我的錯並沒有給它足夠的時間讓Toasts在卸載應用之前趕上,當時我認爲這是阻止聽衆的唯一方法。

爲了測試這個,我再次運行了應用程序3秒鐘,並獲得了273次對SignalStrengthListener的調用,並且每次調用時都會生成一個Toast。我停下並關閉了應用程序,Toa​​sts繼續出現幾分鐘。然而,他們最終停在了273 Toast。

長話短說,吐司不適合每秒多次打電話。這是我的錯,不瞭解我的聽衆如何操作。最後,我設置的布爾值和LISTEN_NONE標記成功地向我的監聽器註銷了監聽器。

+0

請讓我知道如果我應該刪除我的問題。 – JParks

相關問題