Android活动onCreate从另一个活动导航时被调用两次

时间:2013-08-13 02:30:58

标签: android android-activity

我有一个应用程序,在用户使用OAuth对webview活动进行身份验证后生成音乐,看起来像这样:主要玩家活动 - OAuth活动 - 回到主要玩家活动。但是,从OAuth活动开始,onCreate方法被调用两次,导致同时生成和播放两个音轨。 以下是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>{

以下是我的OAuth活动中的代码

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);
    }

}

} 由于某种原因,MainActivity的onCreate方法被调用两次......这里发生了什么?

3 个答案:

答案 0 :(得分:7)

您的实施似乎有误。问题是,您正在尝试使用Intent对象导航回MainActivity表单WebActvitity。这是个问题。你不应该这样做。

每当你想回到之前的活动时,你应该只是在当前的Activity中调用finish()。

在我们的场景中,通过在WebActivity中使用Intent,您将为MainActivity创建一个已存在于堆栈(背景)中的新实例。只需在WebActivity中调用finish()就可以关闭它,并且您的MainActivity应该是可见的。

进行以下更改,

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

替换上面这样的方法,

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

答案 1 :(得分:4)

您似乎正在获得第一个活动的多个实例。在第1次活动的清单中使用它:

机器人:launchMode = “singleTop”

在为第二个活动执行startActivity()之后调用finish()

答案 2 :(得分:4)

除了预期的情况之外,我观察到只有那些活动(onCreate)被调用两次,在你的情况下创建新的Thread或Runnable,AsyncTask。 (我相信这是Android中的一个错误。)

解决方案很简单(尽管你可能不喜欢它: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
        }
    }