启动画面仅第二次无法使用

时间:2016-04-15 08:34:20

标签: android android-activity splash-screen activity-lifecycle

请仔细阅读...... 这是我的启动画面和后退按钮的代码。所有工作正常,除非我从应用程序退出第一次,之后没有出现启动画面但是在第一次之后,每次我点击时都会显示启动画面在应用程序图标。为什么第一次退出后没有出现闪屏?如果有任何关于问题的困惑请问我..

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;


    public class SplashScreen extends Activity {
        // Splash screen timer
        private static int SPLASH_TIME_OUT = 3000;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);

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

                /*
                 * Showing splash screen with a timer. This will be useful when you
                 * want to show case your app logo / company
                 */

                @Override
                public void run() {
                    // This method will be executed once the timer is over
                    // Start your app main activity
                    Intent i = new Intent(SplashScreen.this, Login.class);
                    startActivity(i);

                    // close this activity
                    finish();
                }
            }, SPLASH_TIME_OUT);
        }
        //handle back button press
        @Override
        public void onBackPressed()
        {
          //  mIsBackButtonPressed = true;
            super.onBackPressed();
        }

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            finish();

        }
  }



      // for back button

        @Override
        public void onBackPressed() {
           // mIsBackButtonPressed = true;
           // super.onBackPressed();
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle("Exit Application?");
            alertDialogBuilder
                    .setMessage("Click yes to exit!")
                    .setCancelable(false)
                    .setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    // Write your code here to execute after dialog


                                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                                    startMain.addCategory(Intent.CATEGORY_HOME);
                                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startMain.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

                                    startActivity(startMain);
                                    finish();
                                    UploadActivity.isQuit = true;



                                    Toast.makeText(getApplicationContext(), "ThanK U...",
                                            Toast.LENGTH_SHORT).show();
                                }
                            })

                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            dialog.cancel();
                        }
                    });

            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
        public static boolean isQuit = false

清单文件

      <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.mypackage_name">
        <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
 <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_nirvan"
            android:label="@string/app_name"
            android:theme="@style/AppTheme"
            android:clearTaskOnLaunch="true"
            android:allowClearUserData="true"
            >

            <!--
                We will launch BaseActivity as launcher.
                We will check if BaseActivity launch first time and open desired activity and set navigation item selected
            -->

            <activity
                android:name=".SplashScreen"
                android:label="@string/app_name"
                android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name=".Login"
                android:label="@string/app_name"
                android:screenOrientation="portrait">

            </activity>
            <activity android:name=".UploadActivity" />
           <activity android:name=".SearchPeople" />
            <activity android:name=".InviteFriends" />
            <activity android:name=".ContactUs" />

            <activity
                android:name=".Details"
                android:label="@string/title_activity_details" />

        </application>

    </manifest>

登录活动

package com.mypkg;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import com.enventpc_03.nav11.com.R;
//import com.enventpc_03.nav11.SecondTab;

public class Login extends BaseActivity {

    JSONObject jsonobject;
    JSONArray jsonarray;

    ArrayList<String> arealist;
    //ArrayList<GetterSetter> area;

    // Animation
    Animation animTogether;
    ImageView imageView1;

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    //private Spinner spin1;


    EditText editText_name, editText_MobNo, editText_email;
    LoginDataBaseAdapter loginDataBaseAdapter;

    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //handle the local database
        loginDataBaseAdapter = new LoginDataBaseAdapter(this);
        loginDataBaseAdapter = loginDataBaseAdapter.open();




        // //////////////initializing variables for shortcut on home during
        // installation//
        Context mContext = Login.this;
        SharedPreferences appPreferences;
        boolean isAppInstalled = false;
        // ----Shared pref. for shortcut on home during installation
        // starts------//
        appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        isAppInstalled = appPreferences.getBoolean("isAppInstalled", false);



        SharedPreferences.Editor editor = appPreferences.edit();
        editor.putBoolean("isAppInstalled", true);
        editor.commit();


        cd = new ConnectionDetector(getApplicationContext());

        // get Internet status
        isInternetPresent = cd.isConnectingToInternet();


        Button login = (Button) findViewById(R.id.button_register);
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                cd = new ConnectionDetector(getApplicationContext());

                // get Internet status
                isInternetPresent = cd.isConnectingToInternet();




                EditText user = (EditText) findViewById(R.id.editText_enter_name);
                EditText mobile = (EditText) findViewById(R.id.editText_mobNo);
                EditText email = (EditText) findViewById(R.id.editText_email);

                //loginDataBaseAdapter.insertEntry(user, mobile, email);


                // Check The Validity of empty fields
                boolean Resp = validate(new EditText[]{user});

                // Check The Validity of emailID
                //  boolean e_valid = isEmailValid(email.getText());

                // Check The Validity of Mobile Numbers
                boolean mobile_valid = isMobValid(mobile.getText());

                if (Resp && mobile_valid) {

                    PostJson();
                } else {
//                  Toast.makeText(Login.this, "Field incorrect..!!!",
//                          Toast.LENGTH_SHORT).show();
                }

                if (Resp) {
                    String pass = mobile.getText().toString();
                    if (TextUtils.isEmpty(pass) || pass.length() < 10) {
                        Toast.makeText(Login.this,
                                "Mobile number should be of 10 digits..",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }// Chk Validation of mobile number

                    if (mobile_valid) {
                        if (isInternetPresent) {

                            Toast.makeText(Login.this, "Connecting....", Toast.LENGTH_LONG)
                                    .show();
                        } else {

                            Toast.makeText(Login.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }
            }



            public boolean isMobValid(Editable mobile) {

                boolean isOk = false;

                String exp = "^[0-9]{10}$";
                CharSequence inputStr = mobile;

                Pattern pattern = Pattern
                        .compile(exp, Pattern.CASE_INSENSITIVE);
                Matcher matcher = pattern.matcher(inputStr);
                if (matcher.matches()) {
                    isOk = true;
                }
                return isOk;
            }

            public boolean validate(EditText[] fields) {
                // TODO Auto-generated method stub
                for (int i = 0; i < fields.length; i++) {
                    EditText currentField = fields[i];
                    if (currentField.getText().toString().length() <= 0) {

                        Toast.makeText(Login.this, "Enter all the fields..!!!",
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }
                return true;
            }
        });
    }

    // ==========//

    // Function to display simple Alert Dialog- success/failure (used to set
    // icon)
    public void showAlertDialog(Context context, String title, String message,
                                Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Showing Alert Message
        alertDialog.show();
    }

    // ==================================================================================================================//

    // == To Pupolate the City/Zone Spinner ==//

    // ================= Populatin City/Zone Spinner Ends=======//



    // =========================== Json Object==================//

    public void PostJson() {

        AsyncHttpClient client = new AsyncHttpClient();
        final RequestParams params = new RequestParams();

        EditText user = (EditText) findViewById(R.id.editText_enter_name);
        EditText mobile = (EditText) findViewById(R.id.editText_mobNo);
        EditText email = (EditText) findViewById(R.id.editText_email);

        //spin1 = (Spinner) findViewById(R.id.spinner1);

        //Local database
        editText_name = (EditText) findViewById(R.id.editText_enter_name);
        editText_MobNo = (EditText) findViewById(R.id.editText_mobNo);
        editText_email = (EditText) findViewById(R.id.editText_email);

//////////////////////////////////////////////////////////////////////////////////
        final String source = "Android";
        final String user_name = user.getText().toString();
        final String mobile_no = mobile.getText().toString();
        final String email_id = email.getText().toString();
        String indate = Settings.Secure.getString(this.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        Toast.makeText(this, indate, Toast.LENGTH_SHORT).show();

        //final String area = spin1.getSelectedItem().toString();

        params.put("source", source); // /parameters need to post.
        params.put("user", user_name); // /parameters need to post.
        params.put("email_id", email_id); // /parameters need to post.
        params.put("mobile", mobile_no); // /parameters need to post.
        params.put("indate", indate);
        //  params.put("area", area); // /parameters need to post.

//
//        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Login.this);

        String Url = "myurl/user_login/index.php";
        client.get(Url, params, new JsonHttpResponseHandler() {

            @Override
            public void onStart() {
                System.out.println("Starting request");
            }

            @Override
            public void onSuccess(JSONObject response) {

                try {
                    String mesaage = response.getString("message");
                    String success = response.getString("success");
                    String user_id = response.getString("user_id");

                    if (success.equalsIgnoreCase("0")) {
                        Toast.makeText(Login.this, mesaage, Toast.LENGTH_LONG)
                                .show();
                    } else {

                        Toast.makeText(Login.this, mesaage, Toast.LENGTH_LONG)
                                .show();

                        // if email and mb is valid than login

                        Intent i1 = new Intent(Login.this, UploadActivity.class);
                        startActivity(i1);
                        finish();
                       //local database
                        String userName = editText_name.getText().toString();
                        String mob = editText_MobNo.getText().toString();
                        String email = editText_email.getText().toString();
                        loginDataBaseAdapter.insertEntry(userName, mob, email);



                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                        SharedPreferences.Editor editor = preferences.edit();
                        // save in cache memory
                        editor.putString("MOB", mobile_no);
                        editor.commit();



                        /*
                         * Intent i1 = new Intent(Login.this, Splash.class);
                         * startActivity(i1); finish();
                         */
                        // //////// { onFinish body}///////////////////////////////

                        Log.e("FINISHED_LOG", "onFinish request");

                        SharedPreferences settings = getSharedPreferences(
                                Login.PREFS_NAME, MODE_MULTI_PROCESS);
                        SharedPreferences.Editor editor1 = settings.edit();

                        // Set "hasLoggedIn" to true
                        editor1.putBoolean("hasLoggedIn", true);

                        // Commit the edits!
                        editor1.commit();

                        // ////////////////////////////////////////////////////////

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable e, String response) {


                Log.e("ERROR_LOG", "onFailure request" + e.toString());
                Toast.makeText(Login.this, "Error in Connection.....",
                        Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFinish() {
                // //////// { onFinish body}///////////////////////////////
                    super.onFinish();


                // ////////////////////////////////////////////////////////

            }
        });
    }

    // ==========================Re-Start/Ending of
    // project=============================================//
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();

        finish();

    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        SharedPreferences settings = getSharedPreferences(Login.PREFS_NAME, 0);
        boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
        if (hasLoggedIn) {
            // Go directly to main activity
            Intent i1 = new Intent(Login.this, SplashScreen.class);
            startActivity(i1);
            finish();
        }

    }

    // ==========================Re-Start/Ending of
    // project=============================================//

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        SharedPreferences settings = getSharedPreferences(Login.PREFS_NAME, 0);
        // Get "hasLoggedIn" value. If the value doesn't exist yet false is
        // returned
        boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);

        if (hasLoggedIn) {
            // Go directly to main activity
            Intent i1 = new Intent(Login.this, UploadActivity.class);
            startActivity(i1);
            finish();
        }
    }




}

1 个答案:

答案 0 :(得分:0)

这应该是你的启动画面

   public class SplashScreen extends Activity { 
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_layout);

    Thread thread=new Thread(){
        @Override
        public void run() {
            super.run();
            try {
                sleep(3*1000);
                Intent intent=new Intent(SplashScreen.this,MainActivity.class);
                startActivity(intent);
                finish();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();

}}  

// Android Manifest // Intent Fileter(MAIN和LAUNCH都在.Splash内)

  <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="###############33"/>
    </activity>
    <activity android:name=".SplashScreen"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>