0

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • hi,search for " splash screen" on google, i think that is what you are looking for, you just have to make a check on a preference which would have the last time shown and the time today to see if it was already available today – Andres L Apr 26 '13 at 06:58
  • Here is what you are looking for http://stackoverflow.com/questions/15452061/android-splash-screen – Jibran Khan Apr 26 '13 at 07:00
  • Hi thx for your help but I already got a splash screen. I forgot to say this. It is in my third activity (which is my main) that i want to show some explanation and advertisement made by me (because I got others products). – Thomas Pancani Apr 26 '13 at 07:01
  • Thomas, You need to start a new question. What you are asking now is totally unrelated to your original question. – britzl May 07 '13 at 12:34

2 Answers2

2

Try this code

public class MainActivity extends Activity {

Random random = new Random();
int max = 2;
int min = 0;

ImageView imageView;

Integer[] image = { R.drawable.ic_launcher, R.drawable.tmp,R.drawable.android };

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    int randomNumber = random.nextInt(max - min + 1) + min;

    imageView = (ImageView) findViewById(R.id.img);

    imageView.setImageResource(image[randomNumber]);

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent intent = new Intent(MainActivity.this, Act.class);
            startActivity(intent);
        }
    }, 5000);
  }
}
Ronak Mehta
  • 5,971
  • 5
  • 42
  • 69
0

Ok, so you want to show an image for 5 seconds and you don't want to show the image more often than once a day? This implies that you need to keep track of when you showed the image last, SharedPreferences works well for this. I suggest that you use a custom AlertDialog to show the image. It will look nice and it will dim out the activity in the background. And I'd recommend the use of a Timer and a TimerTask to dismiss the dialog after a certain period of time. Here's an example:

 /**
 * imageIds is an array of drawable resource id to chose from
 * Put the images you like to display in res/drawable-nodpi (if you
 * prefer to provide images for several dpi_bracket you put them in
 * res/drawable-mpdi, drawable-hdpi etc).
 * Add each of their resource ids to the array. In the example
 * below I assume there's four images named myimage1.png (or jpg),
 * myimage2, myimage3 and myimage4. 
 */
@Overrride
public void onCreate(Bundle savedInstanceState) {
    final int[] imageIds = { R.drawable.myimage1, R.drawable.myimage2, R.drawable.myimage3, R.drawable.myimage4 };
    final int id = new Random().nextInt(imageIds.length - 1);  
    showImageDialog(id, 24 * 60 * 60 * 1000, 5000);
}

/**
* Show an image in a dialog for a certain amount of time before automatically dismissing it
* The image will be shown no more frequently than a specified interval
* @param drawableId A resource id for a drawable to show
* @param minTime Minimum time in millis that has to pass since the last time an aimage was shown
* @param delayBeforeDismiss Time in millis before dismissing the dialog 
*
*/
private void showImageDialog(int drawableId, long minTime, long delayBeforeDismiss) {
    final SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    // make sure we don't show image too often
    if((System.currentTimeMillis() - minTime) < prefs.getLong("TIMESTAMP", 0)) {
        return;
    }

    // update timestamp
    prefs.edit().putLong("TIMESTAMP", System.currentTimeMillis()).commit();

    // create a custom alert dialog with an imageview as it's only content
    ImageView iv = new ImageView(this);
    iv.setBackgroundDrawable(getResources().getDrawable(drawableId));       
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(iv);
    final AlertDialog dialog = builder.create();
    dialog.show();

    // dismiss it after 5 seconds
    new Timer().schedule(new TimerTask() {          
        @Override
        public void run() {
            dialog.dismiss();
        }
    }, delayBeforeDismiss);
}
britzl
  • 10,132
  • 7
  • 41
  • 38
  • Thx I'll try this ! Just to be sure this code doesn't choose a random image right ? Still, really big thx ! I'll adapt Rstar's answer with yours to combine the "random" thing and the "once a day" thing. – Thomas Pancani Apr 26 '13 at 07:51
  • Correct. It does not chose between random images. I'll update my answer. – britzl Apr 26 '13 at 10:44
  • BTW There's no problem with the part of your code that chose a random image. I've kept that bit in my updated example. – britzl Apr 26 '13 at 10:52
  • Thank you, I've got a problem to understand this line : int id = getResources().getIdentifier("img" + rndInt, "drawable", getPackageName()); What do I have to put in "img" etc... and this line : showImageDialog(id, what id ? Sorry for these questions I'm not very familiar with all this. – Thomas Pancani Apr 26 '13 at 12:42
  • Oh, sorry, the getResources().getIdentifier("img" + rndInt); was from your own example. I thought you understood what it did. I'll update my example again. – britzl Apr 26 '13 at 18:44
  • Did you try this? If you're happy with the answer you might consider accepting and upvoting. Thanks. – britzl Apr 29 '13 at 05:58
  • Thanks, I didn't have the time to try this... I will try it today. Thank you for your help ! – Thomas Pancani Apr 29 '13 at 06:22
  • It's working ! My boss just asked me to load the images from his website... Do you know how to do the same thing but loading the images from a website ? If it's complicated don't bother you. – Thomas Pancani Apr 29 '13 at 07:21
  • It's a bit more complex to load from a server, but it's not super hard. Some things you need to deal with are bad connections, slow connections etc. You need to add some kind of progress/spinner to prevent a user from thinking that the application has crashed etc. Steps involved: Randomize between a String array of URLs to images. Use an HTTP client to get an InputStream to the URL. Pass the InputStream to BitmapFactory.decodeStream(). Set the Bitmap using ImageView.setImageBitmap(). Post a new question if you need a detailed answer, but give it a try yourself first! – britzl Apr 29 '13 at 07:41
  • Ok thank you with google and your answer it won't be that hard. – Thomas Pancani Apr 29 '13 at 07:51