我的 Activity 中有一些SwitchCompat
,我将其设置OnCheckedChangeListener
为其中之一,但是(使用SharedPreferences
),每次启动 Activity 时,都会执行 OnCheckedChangeListener 的操作,无论它是打开还是关闭(这对性能非常不利,因为状态动作是运行一个 shell 脚本并显示一个SnackBar
,因为它需要一些时间)。
这是一小段代码......
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//Private stuffs...
SwitchCompat play; //and many others
public static final String PREFS_NAME = "SwitchButton";
protected void onCreate(Bundle savedInstanceState) {
// ...
play = (SwitchCompat) findViewById(R.id.play_switch);
play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Shell.SU.run("sh /data/data/br.com.packagename/play_on");
Snackbar snack_play_on = Snackbar.make(play, R.string.play_on, Snackbar.LENGTH_SHORT);
snack_play_on.show();
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", true);
editor.apply();
} else {
Shell.SU.run("sh /data/data/br.com.packagename/play_off");
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", false);
editor.apply();
Snackbar snack_play_off = Snackbar.make(play, R.string.play_off, Snackbar.LENGTH_SHORT);
snack_play_off.show();
}
}
});
play.setChecked(sharedPrefs.getBoolean("onPlay", false));
所以...每次打开 Snackbar 显示的活动(不是应用程序本身)时,与 SwitchCompat 的 On 状态的链接操作都会运行。这会导致加载 Activity 时跳帧过多(在 1GB、1.2GHz 四核设备中约为 230)。开关不止一个,四五个。
我应该怎么办?我是否遗漏了什么或将代码放在错误的位置?我应该使用其他方法,如 OnResume、OnPause 等吗?