6.4Android编程权威指南(第3版)————第六章代码(报告编译版本、限制作弊次数)

报告编译版本 关键代码
xml文件

 <TextView
        android:id="@+id/tv_compile_version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:padding="10dp"/>

java文件

 private TextView mTvCompileVersion;
 mTvCompileVersion = findViewById(R.id.tv_compile_version);
 //获取设备编译版本并显示
 nt apiLevel = Integer.valueOf(Build.VERSION.SDK_INT);
 mTvCompileVersion.setText("API level:"+apiLevel);

限制作弊次数 关键代码
工具类

public class PreferencesUtils {
    public static void putInt(Context context, String key, int value) {
        SharedPreferences sp = context.getSharedPreferences("counttab", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt(key, value);
        edit.commit();
    }

    public static int getInt(Context context, String key, int value) {
        SharedPreferences sp = context.getSharedPreferences("counttab", Context.MODE_PRIVATE);
        return sp.getInt(key, 0);
    }
}

java文件

 private int cheatCount = 0;//作弊次数
 private String EXTRA_COUNT = "count";
 mCheatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cheatCount = PreferencesUtils.getInt(getApplication(), EXTRA_COUNT, 0);
                if (PreferencesUtils.getInt(getApplication(), EXTRA_COUNT, 0) < 3) {
                    boolean answerTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
                    Intent intent = CheatActivity.newIntent(QuizActivity.this, answerTrue, mCurrentIndex);
                /*activity调用startActivity(Intent)方法时,调
                用请求实际发给了操作系统。
                准确地说,调用请求发送给了操作系统的ActivityManager。ActivityManager负责创建
                Activity实例并调用其onCreate(Bundle)方法*/
                    startActivityForResult(intent, REQUEST_CODE_CHEAT);
                    cheatCount = cheatCount + 1;
                    PreferencesUtils.putInt(getApplication(), EXTRA_COUNT, cheatCount);
                    Toast.makeText(getApplication(), "您还剩余" + (3 - cheatCount) + "次可以查看答案", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplication(), "您已没有剩余查看次数", Toast.LENGTH_SHORT).show();
                }
            }
        });

Demo下载地址:
https://download.csdn.net/download/weixin_43953649/10860923

猜你喜欢

转载自blog.csdn.net/weixin_43953649/article/details/85091819