I'm trying to display a random image for 5 seconds (I've got 3 images) when my main activity is launched. (It's a kind of tutorial how to use my app and some advertisement). But I just want to display it once a day. I need to use SharedPreferences right? It's the best approach to do it, is it? So I found this:
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(n) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
To display a random image. And this:
public class mActivity extends Activity {
@Overrride
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.id.layout);
// Get current version of the app
PackageInfo packageInfo = this.getPackageManager()
.getPackageInfo(getPackageName(), 0);
int version = packageInfo.versionCode;
SharedPreferences sharedPreferences = this.getPreferences(MODE_PRIVATE);
boolean shown = sharedPreferences.getBoolean("shown_" + version, false);
ImageView imageView = (ImageView) this.findViewById(R.id.newFeature);
if(!shown) {
imageView.setVisibility(View.VISIBLE);
// "New feature" has been shown, then store the value in preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.put("shown_" + version, true);
editor.commit();
} else
imageView.setVisibility(View.GONE);
}
To show once an app is updated the current version of the app. I tried to adapt those codes for my app but I failed. I also need that the image has to be displayed just 5 seconds and close automatically.
Hey it's me again. I got this code now and it works perfectly:
boolean firstboot = getSharedPreferences("BOOT_PREF",MODE_PRIVATE).getBoolean("firstboot", true);
getSharedPreferences("BOOT_PREF",MODE_PRIVATE).edit().
putBoolean("firstboot", true).commit();
if(firstboot){
Intent webBrowser = new Intent(getApplicationContext(), WebBrowser.class);
// dismiss it after 5 seconds
webBrowser.putExtra("url", "http://sce.jelocalise.fr/mobile/ajax/interstitiel.php");
startActivity(webBrowser);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent MyIntent = new Intent(getApplicationContext(), Home.class);
startActivity(MyIntent);
}
}
}, 5000);
getSharedPreferences("BOOT_PREF",MODE_PRIVATE).edit().
putBoolean("firstboot", false).commit();
}
What I want now: there is a cancel button on my webview and when I click on it, it finishes the webBrowser activity. The problem is when I click on the cancel button the handler doesn't stop, and after 5 seconds it reloads the Home activity (which is normal I know). I just want that the cancel button kills the handler. I've tried handler.removeCallbacks method but I didn't really understand how it works.