Попробуйте код ниже, объяснения внутри кода:
public class MainActivity extends AppCompatActivity {
private int lastCheck = 0;
private SharedPreferences pref;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
//GET THE LAST CHECKED DATE FROM SHARED PREFERENCES, WE ARE USING DAY OF A MONTH
lastCheck = pref.getInt("lastcheck", 0);
//GET THE NUMBER OF TIMES THE ACTIVITY WAS OPENED FROM SHARED PREFERENCES
int count = pref.getInt("count", 0);
// IF IT IS A NEW DAY START COUNTING FROM 0 AGAIN
if(isNewDay()){
count = 0;
}
// IF COUNT REACHES 5 CLOSE THE ACTIVITY. YOU CAN USE ANY OTHER MEANS TO BLOCK IT.
if (count >= 5){
finish();
}
else{
// ELSE INCREMENT COUNT AND SAVE IT IN THE SHARED PREFERENCES
count++;
editor.putInt("count", count);
editor.commit();
}
}
// GET THE CURRENT DAY IN THE MONTH AND COMPARE IT WITH THE LAST CHECKED
public boolean isNewDay() {
Date date = new Date();
int today = Integer.parseInt(DateFormat.format("dd", date).toString());
boolean ret = lastCheck == 0 || today > lastCheck;
lastCheck = today;
return ret;
}
}