6.4Android程式設計權威指南(第3版)————第六章程式碼(報告編譯版本、限制作弊次數)
阿新 • • 發佈:2018-12-19
報告編譯版本 關鍵程式碼
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