2016-02-24 1 views
1

У меня есть приложение со многими действиями с использованием намерений. У меня есть метод sharedPreferences для сохранения значений.OnPause(), а также onDestroy() никогда не вызывали при открытии другой активности

У меня есть экран приветствия, который я установил для отображения при запуске приложения (вызывается onCreate). В том же действии я удаляю метод sharePreferences, поэтому, когда я снова открываю приложение, экран приветствия снова запустится.

Проблема заключается в том, что я перехожу к другому действию и снова возвращаюсь к основному виду деятельности и нажимаю кнопку выхода. Когда я снова запускаю приложение, он не отображает экран приветствия. Я думаю, основное действие все еще выполняется, поэтому onPause(), onStop() и onDestroy() никогда не вызываются. Когда я остаюсь в том же самом действии (main) и нажмите exit, он вызывается onDestroy() (который содержит метод erase sharedPreferences).

Я не установил метод finish(). Если я установил это, каждая перемещенная деятельность вызовет onDestroy в основной деятельности, поэтому экран приветствия начнет каждый переход к этой активности.

Мой mainactivity.java

package com.bani.latihan; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.res.Configuration; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.RelativeLayout; 

public class Main extends AppCompatActivity { 


RelativeLayout PopupScreen, layoutAsli; 

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
} 

@Override 
public void onDestroy(){ 
    super.onDestroy(); 


     SharedPreferences settings =  getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE); 
     settings.edit().remove("ditekan").apply(); 




} 



@Override 
public void onCreate(Bundle savedInstanceState) { 
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    super.onCreate(savedInstanceState); 
    getSupportActionBar().setDisplayShowHomeEnabled(true); 
    getSupportActionBar().setLogo(R.mipmap.ic_launcher); 
    getSupportActionBar().setDisplayUseLogoEnabled(true); 
    setContentView(R.layout.main); 

    Button btn1 =(Button)findViewById(R.id.button1); 
    final Button btn2 =(Button)findViewById(R.id.button2); 
    PopupScreen = (RelativeLayout)findViewById(R.id.PopupScreen); 
    layoutAsli = (RelativeLayout)findViewById(R.id.layoutAsli); 

    btn1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Intent intent2 = new Intent(Main.this, Intent2.class); 
      startActivity(intent2); 


     } 
    }); 

    btn2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      moveTaskToBack(true); 

      finish(); 



     } 
    }); 




    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Isi dewek cuk!", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

    EditText tvText = (EditText) findViewById(R.id.editText1); 

    SharedPreferences prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE); 
    if (prefs.contains("text")){ 
     tvText .setText(prefs.getString("text", "")); 
    } 
    SharedPreferences prefs2 = getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE); 
    if (prefs2.contains("ditekan")){ 
     PopupScreen.setVisibility(View.INVISIBLE); 
     layoutAsli.setVisibility(View.VISIBLE); 
    } 


} 
public void dismisWelcomeMessageBox(View view) { 
    PopupScreen.setVisibility(View.INVISIBLE); 
    layoutAsli.setVisibility(View.VISIBLE); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    EditText tvText = (EditText) findViewById(R.id.editText1); 
    Button btWelcome = (Button) findViewById(R.id.button_welcome); 
    SharedPreferences.Editor prefEditor = getSharedPreferences("Preferences", Context.MODE_PRIVATE).edit(); 
    SharedPreferences.Editor prefEditor2 = getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE).edit(); 
    prefEditor.putString("text", tvText.getText().toString()); 
    prefEditor2.putBoolean("ditekan", btWelcome.isPressed()); 
    prefEditor.apply(); 
    prefEditor2.apply(); 
} 



} 

Мой другой код вида деятельности:

package com.bani.latihan; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.res.Configuration; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.CompoundButton; 
import android.widget.ImageView; 

/** 
    * Created by Bani Burhanuddin on 21/02/2016. 
    */ 
public class Intent2 extends AppCompatActivity { 

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 

} 




@Override 
protected void onCreate(Bundle savedInstanceState) { 
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    super.onCreate(savedInstanceState); 
    getSupportActionBar().setDisplayShowHomeEnabled(true); 
    getSupportActionBar().setLogo(R.mipmap.ic_launcher); 
    getSupportActionBar().setDisplayUseLogoEnabled(true); 
    setContentView(R.layout.intent); 

    Button btnnext = (Button) findViewById(R.id.button5); 
    Button btnhome = (Button) findViewById(R.id.button6); 
    Button btnback = (Button) findViewById(R.id.button7); 

    btnnext.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      startActivity(new Intent(Intent2.this, Intent3.class)); 
      finish(); 

     } 
    }); 

    btnhome.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      startActivity(new Intent(Intent2.this, Main.class)); 
      finish(); 

     } 
    }); 

    btnback.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      startActivity(new Intent(Intent2.this, Main.class)); 
      finish(); 

     } 
    }); 

    CompoundButton toggle = (CompoundButton) findViewById(R.id.switch1); 
    final ImageView imageView2 = (ImageView) findViewById(R.id.imageView2); 
    imageView2.setVisibility(View.GONE); 
    toggle.setOnCheckedChangeListener(new  CompoundButton.OnCheckedChangeListener() { 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) { 

       imageView2.setVisibility(View.VISIBLE); 
      } else { 

       imageView2.setVisibility(View.GONE); 
      } 
     } 
    }); 


    SharedPreferences prefs = getSharedPreferences("Preferences2", Context.MODE_PRIVATE); 
    if (prefs.contains("text2")) { 
     toggle.setChecked(prefs.getBoolean("text2", true)); 
    } 


} 

@Override 
public void onPause() { 
    super.onPause(); 

    CompoundButton toggle = (CompoundButton) findViewById(R.id.switch1); 
    if (toggle.isChecked()) { 
     SharedPreferences.Editor editor = getSharedPreferences("Preferences2", MODE_PRIVATE).edit(); 
     editor.putBoolean("text2", true); 
     editor.apply(); 
    } else { 
     SharedPreferences.Editor editor = getSharedPreferences("Preferences2", MODE_PRIVATE).edit(); 
     editor.putBoolean("text2", false); 
     editor.apply(); 
    } 


} 



} 

Мой Manifest

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <!-- Splash screen --> 

    <activity 
     android:name="com.bani.latihan.splashscreen" 
     android:label="@string/app_name" 
     android:screenOrientation="sensor" 
     android:configChanges="keyboardHidden|orientation|screenSize" 
     android:noHistory="true"> 


     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 


    <!-- Main activity --> 

    <activity 
     android:name="com.bani.latihan.Main" 
     android:screenOrientation="sensor" 
     android:label="@string/app_name" 
     android:configChanges="keyboardHidden|orientation|screenSize"> 

    </activity> 

    <!-- Intent2 activity --> 

    <activity 
     android:name=".Intent2" 
     android:screenOrientation="sensor" 
     android:noHistory="true" 
     android:configChanges="keyboardHidden|orientation|screenSize"> 
    </activity> 

    <!-- Intent3 activity --> 

    <activity 
     android:name=".Intent3" 
     android:screenOrientation="sensor" 
     android:configChanges="keyboardHidden|orientation|screenSize"> 
    </activity> 

    <!-- Intent4 activity --> 

    <activity 
     android:name=".Intent4" 
     android:screenOrientation="sensor" 
     android:configChanges="keyboardHidden|orientation|screenSize"> 
    </activity> 

</application> 

</manifest> 

Мой главный макет

<RelativeLayout 
    android:id="@+id/PopupScreen" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#123456" 
    android:orientation="vertical" 
    android:layout_margin="16dp" 
    android:padding="16dp" 
    android:visibility="visible"> 

    <TextView 
     android:id="@+id/welcome_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="16dp" 
     android:layout_marginTop="16dp" 
     android:text="@string/welcome" 
     android:textColor="#ddd333" 
     android:textSize="28sp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/welcome_message" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/welcome_title" 
     android:text="@string/welcome_message" 
     android:textColor="#0dff00" 
     android:textSize="18sp" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:id="@+id/button_welcome" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_gravity="bottom" 
     android:background="#3b978d" 
     android:onClick="dismisWelcomeMessageBox" 
     android:paddingLeft="30dp" 
     android:paddingRight="30dp" 
     android:text="@string/ok" 
     android:textColor="#fff" /> 
</RelativeLayout> 



<RelativeLayout 
    android:id="@+id/layoutAsli" 
    android:visibility="invisible" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    android:id="@+id/hello_world"/> 
    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/editText1" 
     android:layout_below="@+id/hello_world"/> 

<FrameLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/imageView" 

     android:src="@drawable/imageview" 
     android:layout_gravity="center" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Next" 
     android:id="@+id/button1" 
     android:layout_marginTop="111dp" 
     android:layout_centerHorizontal="true" 
     android:layout_gravity="left|bottom" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Exit" 
     android:id="@+id/button2" 
     android:layout_below="@+id/button1" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="59dp" 
     android:layout_gravity="right|bottom" /> 


</FrameLayout> 


</RelativeLayout> 


</RelativeLayout> 

ответ

0

У меня проблема с ур. В настоящее время вы используете MoveTaskToBack. Он не уничтожит активность, а просто вернется в стек ativity после этого u завершает работу . Таким образом, он не вызывает другие методы обратного вызова. Он всегда вызывает onDestroy Используйте либо moveTasktoBack, либо завершите. Не используйте оба варианта, это будет путать.

+0

Youre right! Но я кое-что понимаю. Когда я нажимаю следующую кнопку, он создает одно и то же действие и делает двойную основную активность. Поэтому, если я воплощу ваше предложение, оно запустит приветственный экран, поскольку мне нужно. Но я должен нажать кнопку выхода дважды. Таким образом, это означает, что есть две (основные) операции, или мы можем назвать это двойной деятельностью. –

+0

У меня есть другое решение, поэтому теперь я использую этот метод finishAffinity(); Он закроет все фоновые действия, поэтому я могу очень хорошо позвонить по телефону. –

Смежные вопросы