我是在 Android 操作系统中编程的初学者,这就是我决定向您寻求帮助的原因。我的问题与PhoneStateListener
应该根据切换按钮状态调用哪个有关:
togglebtn==ON
- 如果 ServiceStateChanges 或 DataConnectionStateChanges -> 在屏幕上打印 Toast
togglebtn==OFF
- 不检查 ServiceStateChanges 或 DataConnectionStateChanges
我发现为了停止监听,我应该将LISTEN_NONE
参数作为参数发送到监听方法,但它不起作用
这是我的代码的最简单版本:
package network.com.example;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
ToggleButton button_on_off=(ToggleButton)findViewById(R.id.toggleButton1);
button_on_off.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
nw_update(tm , "onCRE");
tm.listen(new PhoneStateListener() {
@Override
public void onServiceStateChanged(ServiceState serviceState) {
nw_update(tm , "onSSC");
}
@Override
public void onDataConnectionStateChanged(int state) {
nw_update(tm , "onDCC");
}
}, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
}
else
{
tm.listen(null, PhoneStateListener.LISTEN_NONE | PhoneStateListener.LISTEN_NONE );
}
}
}); // end of button on/off
} // end of onCreate
private final void nw_update(TelephonyManager tm , String rodzaj) {
String _rodzaj = rodzaj;
Toast.makeText(getApplicationContext(), _rodzaj, Toast.LENGTH_SHORT).show();
}
} // end of main activity
有任何想法吗?我期待着您的回音。