Android onCreate Called Twice action when navigating from another action

I have an application that generates music after a user authenticates with OAuth in web browsing activity, looking something like this: main player activity - OAuth activity - return to the main player activity. However, the onCreate method is called twice when switching from OAuth activity, as a result of which two audio tracks are generated and played simultaneously. Here is the code part from MainActivity:

public class MainActivity extends Activity { int pitch=60; private static final float VISUALIZER_HEIGHT_DIP = 50f; Random rn; boolean isRunning = true; boolean isPlaying=false; SeekBar fSlider; double sliderval; MediaPlayer mediaPlayer=new MediaPlayer(); ImageButton startStopButton; ImageButton stopButton; SeekBar vSlider; VisualizerView mVisualizerView; private Visualizer mVisualizer; ImageButton connectButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // point the slider to the GUI widget rn = new Random(); fSlider = (SeekBar) findViewById(R.id.frequency); fSlider.setProgress(0); vSlider= (SeekBar) findViewById(R.id.seekBar2); vSlider.setMax(10); vSlider.setProgress(0); TextView viewinterval=(TextView) findViewById(R.id.textView2); viewinterval.setText(""); startStopButton=(ImageButton) findViewById(R.id.imageButton2); View activity= this.findViewById(R.id.playerActivity); stopButton=(ImageButton) findViewById(R.id.imageButton1); RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density)); params.addRule(RelativeLayout.BELOW, R.id.seekBar2); mVisualizerView = new VisualizerView(this); mVisualizerView.setLayoutParams(params); ((ViewGroup) activity).addView(mVisualizerView); connectButton=(ImageButton) findViewById(R.id.imageButton3); connectButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { mediaPlayer.pause(); Intent intent= new Intent(getApplicationContext(), WebViewActivity.class); startActivity(intent); } }); if(riskscores.length !=0){ viewinterval.setText("generating audio"); new MIDISequence().execute(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onPause() { super.onPause(); if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); } } class MIDISequence extends AsyncTask<String,Void,String>{ 

Here is the code from my OAuth activity

 public class WebViewActivity extends Activity { private WebView gWebView; final String REDIRECT_URI = "https://localhost:5000/receive_code"; final String CLIENT_ID = "can't post it here"; final String CLIENT_SECRET = "can't post it here"; final String SCOPE = "basic names genomes analyses"; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.webview); gWebView = (WebView) findViewById(R.id.webView1); gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri=" + REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID + "&scope=" + SCOPE); Log.d("WEBVIEW", "got to webpage"); gWebView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (url.startsWith(REDIRECT_URI)) { Log.d("WEBVIEW", "onpagefinished is called"); System.out.println("got to override"); if (url.indexOf("code=") != -1) { //if the query contains code String queryString = null; try { queryString = new URL(url).getQuery(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(queryString); String[] params = queryString.split("&"); String code = null; for (String param : params) { if (param.startsWith("code=")) { code = param.substring(param.indexOf('=') + 1); } } gWebView.setVisibility(View.GONE); new PostRequest().execute(code); // don't go to redirectUri } } } }); } class PostRequest extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... params) { code retrieving client data..... } catch (ClientProtocolException e) { // TODO Auto-generated catch block System.out.println("CPE" + e); } catch(SocketException ex) { Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage()); ex.printStackTrace(); return "error occured"; } catch (JSONException e) { e.printStackTrace(); return "error occured"; } catch (IllegalStateException e) { e.printStackTrace(); return "error occured"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return "error occured"; } } return "request complete"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("Post result", result); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } } 

} The onCreate MainActivity method is called twice for some reason ... What is happening here?

+4
source share
3 answers

There seems to be a mistake in your implementation. The point is that you are trying to use an Intent object to navigate to your MainActivity WebActvitity form. This is problem. You must not do this.

Whenever you want to return to the previous action, you just have to call finish () in the current Activity.

In our scenario, using the Intent in your WebActivity, you create a new instance for your MainActivity that already exists on the stack (background). Just calling finish () in WebActivity should close it, and your MainActivity should be visible.

Make the following changes:

 @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("Post result", result); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } 

Replace the above method as follows:

 @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.d("Post result", result); finish(); } 
+7
source

It seems you are getting several instances of your first activity. use this in the manifest of the 1st activity:

Android: launchMode = "SingleTop"

else call finish () after executing startActivity () for the 2nd action

+4
source

In addition to the expected cases, I noticed that only those actions (onCreate) are called twice that create your Thread or Runnable, AsyncTask in your case. (I believe this is a bug in Android).

The solution is simple (although you may not like it: p)

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); if(savedInstanceState == null){ // everything else that doesn't update UI } } 
+4
source

Source: https://habr.com/ru/post/1496697/


All Articles