PhoneStateListener不会发布,也没有以前发布的答案

时间:2015-11-03 22:51:03

标签: android telephonymanager phone-state-listener

这个问题之前已被多次询问,而且他们中的任何一个人都没有一个问题解决了这个问题。我已经尝试了通过按下按钮,进入onPause和onDestroy来取消注册我的监听器的所有方法。但即使应用程序关闭,听众仍然存在。更重要的是,我正在敬酒我的听众正在填充的数组大小,即使应用程序关闭,Toast仍然存在并继续增加。我尝试过使用null和LISTEN_NONE以及我在网上找到的所有其他内容。

// 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项目,请告诉我。

谢谢!!!

1 个答案:

答案 0 :(得分:0)

我想我弄清楚发生了什么。我在代码中添加了一些Log.d()语句来确定SignalStrengthListener被调用了多少次。我运行应用程序3秒钟,发现SignalStrengthListener被调用了大约300次!比我想象的要多得多。现在的问题是,Toast无法跟上它被调用的次数;所以当我停止或关闭应用程序时,Toasts会在几分钟后继续出现。在卸载应用程序之前,我的错误是没有足够的时间让Toasts赶上来,当时我认为这是阻止听众的唯一方法。

为了测试这个,我再次运行应用程序3秒钟,并对SignalStrengthListener进行了273次调用,并且每次调用它都会进行Toast。我停下来关闭了应用程序,Toa​​sts继续出现几分钟。然而,他们终于在273 Toast停了下来。

长话短说,Toast不适合一秒钟多次调用。这是我不理解我的听众如何运作的错。最后,我设置的布尔值和我的监听器的LISTEN_NONE标签成功取消注册了监听器。