1

My app uses Barcode Scanner. I want to launch the scanner when I open the app so I have it in the onCreate method. The problem is that if I have it like that, when I turn the device it calls again onCreate and calls another scanner.

Also I have the first activity that calls the scanner. it has a menu so if the user presses back, it goes to that menu. If I turn the screen on that menu, it goes to barcode scanner again.

To solve it I have a flag that indicates if it is the first time I call the scanner, if it's not I don't call it again. Now the problem is that if I go out of the app and go in again it doesn't go to the scanner, it goes to the menu, becasuse is not the first time I call it.

Any ideas? Is there a way to change the flag when I go out of my main activity or any other solution? My code.

private static boolean first = true;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    integrator = new IntentIntegrator(this);
    if (first) {
        first = false;
        integrator.initiateScan();
    }

}
Djkgotso
  • 130
  • 2
  • 4
  • 15

2 Answers2

3

In your Application manifest.xml, add this to your Activity where this barcode scanner is called

android:configChanges="orientation"

like this

<activity
android:name=".YourActivity"
android:configChanges="orientation"
android:label="@string/app_name" />

what it does is, when the device is rotated, it will "do nothing" which mean it will not call the activity again (which eventually avoids calling onCreate())

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • I think this doesn't solve if he leaves the app like pressing home button and come back on the home button long press. – Nuno Gonçalves Jun 16 '12 at 08:36
  • 1
    sorry i did'nt get you. what do you mean by "this doesn't solve", can you elaborate on what happens when he clicks home button and comes back to app by selecting recently used apps?? i have no idea about this :(, the solution i posted worked fine for me (though i didnt test all the cases) – Archie.bpgc Jun 16 '12 at 08:40
  • Never mind, I was under the impression "onCreate()" gets called on activity resume. I was wrong. – Nuno Gonçalves Jun 16 '12 at 08:47
1

You can override the onResume method and do whatever changes you'd like.

public void onResume(Bundle savedInstanceState) {
    super.onResume();
//reset the flag here as you wish
}
Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66