【发布时间】:2015-11-03 22:51:03
【问题描述】:
这个问题之前已经被问过很多次了,没有一个回答能帮我解决这个问题。我已经尝试了所有我能找到的方法来取消注册我的监听器,方法是按下一个按钮,进入 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 项目,请告诉我。
谢谢!!!
【问题讨论】:
-
我还没有测试过,但我只能建议你创建全局静态布尔变量,并在应用程序运行时将其标记为真,例如在 onCreate() 中,并在 ondestroy 或 onpause 下标记为假。并且在您的侦听器中放置条件 if(IsApplicationRunning) { //do rest of the stuff } else {//ignore it } 这样即使您的应用程序连接到系统,尽管没有使用,那么至少它会寻找这个条件运行。
-
这是我最近一直在尝试但没有成功的方法。如果您查看上面的代码,就会看到
boolean flag,我已经尝试将它放在许多不同的地方。例如,在上面的代码中,我在 onPause 方法中将标志设置为 true,这应该会阻止侦听器继续执行,但它只会继续执行。我还使用flagbool 将 SignalStrengthListener 中的所有代码包装在 if 语句中。 -
我在 onPause 和 onDestroy 中也有调试 cmets,它们总是打印成功注释,所以我知道侦听器在重新分配“标志”布尔值之前被设置为 LISTEN_NONE。如果您看到我使用
flag布尔值的更合乎逻辑的方式,请告诉我。感谢您的宝贵时间。 -
请发布您的清单
标签: android telephonymanager phone-state-listener