package com.test.sharedpreferences;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
/**
* SharedPreferences 学习2
*/
public class AppUseNumActivity extends AppCompatActivity {
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_use_num);
SharedPreferences preferences = getSharedPreferences("count", MODE_PRIVATE);
count = preferences.getInt("count", 0);
findViewById(R.id.btn_num).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(AppUseNumActivity.this, "程序使用了: " + count + " 次", Toast.LENGTH_SHORT).show();
}
});
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("count", ++count);
editor.commit();
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.sharedpreferences.AppUseNumActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_num"
android:text="查看app使用次数"
/>
</RelativeLayout>