2015-11-03 50 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

相关问题