gpt4 book ai didi

java - 在Android中只创建一个类的一个实例

转载 作者:行者123 更新时间:2023-12-01 11:28:52 27 4
gpt4 key购买 nike

我正在尝试使用 PhoneStateListener,但在关闭监听器时遇到问题。在我的代码中,我创建了 TeleListener 类的一个新实例,该实例扩展了 PhoneStateListener。为了关闭监听器,我需要调用我最初调用的 TeleListener 类的同一实例。但我编写的代码是创建一个新实例,而不是使用现有实例。所以我的问题是,我该如何编写它,以便最初调用一个新实例,然后当我想关闭监听器时,我调用原始实例?我正在使用一个开关打开和关闭监听器,这是现在看起来的开关代码:

    // ---
TeleMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// --- END

// --- switch
switch_SW = (SwitchCompat) findViewById(R.id.mainSwitch_SW);
switch_SW.setTextOn("ON");
switch_SW.setTextOff("OFF");

// --- get switch prefs
switchPref = getSharedPreferences(SWITCH_PREFS, Context.MODE_PRIVATE);
switch_SW.setChecked(switchPref.getBoolean(switchKeyStr, true));

switch_SW.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if (isChecked) {

// ---
TeleMan.listen(tListen, PhoneStateListener.LISTEN_CALL_STATE);
SharedPreferences.Editor swEditor = getSharedPreferences(
SWITCH_PREFS, MODE_PRIVATE).edit();
swEditor.putBoolean(switchKeyStr, true);
swEditor.commit();
Toast.makeText(getApplicationContext(), "ON",
Toast.LENGTH_SHORT).show();

// --- END
} else {

// ---
TeleMan.listen(tListen, PhoneStateListener.LISTEN_NONE);

SharedPreferences.Editor swEditor = getSharedPreferences(
SWITCH_PREFS, MODE_PRIVATE).edit();
swEditor.putBoolean(switchKeyStr, false);
swEditor.commit();
Toast.makeText(getApplicationContext(), "OFF",
Toast.LENGTH_SHORT).show();
// ---
}

}
});// --- END switch

我在这里创建监听器的实例:

public class TestActivity extends AppCompatActivity {
private SwitchCompat switch_SW;

SharedPreferences switchPref;
TelephonyManager TeleMan;

public static final String SWITCH_PREFS = "switchPref";
public static final String switchKeyStr = "switchKey";
new instance --> private TeleListener tListen = new TeleListener();

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

...然后我进入上面的 Switch 代码...

最佳答案

我认为你需要Java Singleton Class Design .

如果您已按照此模式完成,则可以像这样使用它:

TeleMan.getInstance().method();
// ^--- This could be any methods you've defined
// in this singleton.

请注意,TeleMan.getInstance() 返回的所有引用都指向同一内存位置。

TeleMan tm1 = TeleMan.getInstance();
TeleMan tm2 = TeleMan.getInstance();
TeleMan tm3 = TeleMan.getInstance();

tm1 == tm2 == tm3

关于java - 在Android中只创建一个类的一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600695/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com