启动画面延迟计时器等到android中的权限对话框关闭

时间:2017-05-15 14:21:55

标签: android timer gps

我正在Splash Screen中收集GPS位置数据并将其存储在会话中,稍后在MainActivity中使用它。如果GPS首次关闭或使用,它将在我的启动画面中请求许可。问题是我正在使用计时器将启动画面活动移动到另一个活动。由于计时器,SplashScreen将在未经许可的情况下移动到下一个活动。我希望我的Splash屏幕等到允许或拒绝权限对话框。以下是我的代码

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import zesteve.com.myapplication.location.LocationTrack;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;


public class SplashActivity extends AppCompatActivity {

    TextView welcomeText;
    ImageView mLogo;
    ImageView zbgimg;

    Typeface tf1;

    private Session session;

    private ArrayList<String> permissionsToRequest;
    private ArrayList<String> permissionsRejected = new ArrayList<>();
    private ArrayList<String> permissions = new ArrayList<>();

    private final static int ALL_PERMISSIONS_RESULT = 101;
    LocationTrack locationTrack;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        session = new Session(SplashActivity.this);

        //GPS Tracker
        permissions.add(ACCESS_FINE_LOCATION);
        permissions.add(ACCESS_COARSE_LOCATION);

        permissionsToRequest = findUnAskedPermissions(permissions);
        //get the permissions we have asked for before but are not granted..
        //we will store this in a global list to access later.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissionsToRequest.size() > 0)
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
        }

        locationTrack = new LocationTrack(SplashActivity.this);

        if (locationTrack.canGetLocation()) {
            double longitude = locationTrack.getLongitude();
            double latitude = locationTrack.getLatitude();

            Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = gcd.getFromLocation(latitude, longitude, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (addresses != null && addresses.size() > 0) {
                String locality = addresses.get(0).getLocality();
                String subLocality = addresses.get(0).getSubLocality();
                String address = addresses.get(0).getAddressLine(0);
                String state = addresses.get(0).getAdminArea();
                String countryn = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName();


                session.setLocation(latitude,longitude,locality,subLocality);

                //Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
            }
        } else {
            locationTrack.showSettingsAlert();
        }

        welcomeText = (TextView) findViewById(R.id.welcome);
        tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
        welcomeText.setTypeface(tf1);
        mLogo = (ImageView) findViewById(R.id.applogo);
        zbgimg = (ImageView) findViewById(R.id.zbgimg);
        zbgimg.setImageResource(R.drawable.splash_screen_option_three);


        animation2();
        animation3();

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

            @SuppressLint("PrivateResource")
            @Override
            public void run() {
                if (session.FbLoggedIn()) {
                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                    overridePendingTransition(R.anim.entry, R.anim.exit);
                } else {
                    Intent i = new Intent(SplashActivity.this,
                            LoginActivity.class);
                    startActivity(i);
                    finish();
                    overridePendingTransition(R.anim.entry, R.anim.exit);
                }

            }

        }, 3000);
    }


    private void animation2() {
        mLogo.setAlpha(1.0F);
        Animation anim = AnimationUtils.loadAnimation(SplashActivity.this, R.anim.translate_top_to_center);
        mLogo.startAnimation(anim);
    }

    private void animation3() {
        ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
        alphaAnimation.setStartDelay(1700);
        alphaAnimation.setDuration(500);
        alphaAnimation.start();
    }


    ///GPS Tracker
    private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
        ArrayList<String> result = new ArrayList<String>();

        for (String perm : wanted) {
            if (!hasPermission(perm)) {
                result.add(perm);
            }
        }

        return result;
    }

    private boolean hasPermission(String permission) {
        if (canMakeSmores()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
            }
        }
        return true;
    }

    private boolean canMakeSmores() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
    }


    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {

            case ALL_PERMISSIONS_RESULT:
                for (String perms : permissionsToRequest) {
                    if (!hasPermission(perms)) {
                        permissionsRejected.add(perms);
                    }
                }

                if (permissionsRejected.size() > 0) {


                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                            showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                            }
                                        }
                                    });
                            return;
                        }
                    }

                }

                break;
        }

    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(SplashActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationTrack.stopListener();
    }

如果您不明白,请发表评论。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要在从启动画面跳转之前访问位置。如果是这样,只需删除计时器并打开启动画面,使其检查位置服务的开/关并获取位置,然后跳转到另一个活动。

if (!canGetLocation()) {
     showSettingsAlert();
} else {
     fetch location
     if (session.FbLoggedIn()) {
           startActivity(new Intent(SplashActivity.this, MainActivity.class));
           finish();
           overridePendingTransition(R.anim.entry, R.anim.exit);
     } else {
           startActivity(new Intent(SplashActivity.this, LoginActivity.class));
           finish();
           overridePendingTransition(R.anim.entry, R.anim.exit);
    }
}

答案 1 :(得分:1)

尝试此解决方案。

首先,以这种方式制作onCreate()方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    session = new Session(SplashActivity.this);

    //GPS Tracker
    permissions.add(ACCESS_FINE_LOCATION);
    permissions.add(ACCESS_COARSE_LOCATION);

    permissionsToRequest = findUnAskedPermissions(permissions);
    //get the permissions we have asked for before but are not granted..
    //we will store this in a global list to access later.

    welcomeText = (TextView) findViewById(R.id.welcome);
    tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
    welcomeText.setTypeface(tf1);
    mLogo = (ImageView) findViewById(R.id.applogo);
    zbgimg = (ImageView) findViewById(R.id.zbgimg);
    zbgimg.setImageResource(R.drawable.splash_screen_option_three);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (permissionsToRequest.size() > 0)
            requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
    }
    else {
        animation2();
        animation3();
        setUserLocation();   //After that start app
    }

}

然后在onCreate()之外创建单独的setUserLocation()函数,如下所示: -

public void setUserLocation() {

    locationTrack = new LocationTrack(SplashActivity.this);

    if (locationTrack.canGetLocation()) {
        double longitude = locationTrack.getLongitude();
        double latitude = locationTrack.getLatitude();

        Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = gcd.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses != null && addresses.size() > 0) {
            String locality = addresses.get(0).getLocality();
            String subLocality = addresses.get(0).getSubLocality();
            String address = addresses.get(0).getAddressLine(0);
            String state = addresses.get(0).getAdminArea();
            String countryn = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName();

            session.setLocation(latitude,longitude,locality,subLocality);

            //Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
        }

        startApp();

    } else {
        locationTrack.showSettingsAlert();
    }
}

onCreate()之外还有一个单独的函数startApp(),如下所示: -

public void startApp() {
    new Handler().postDelayed(new Runnable() {

        @SuppressLint("PrivateResource")
        @Override
        public void run() {
            if (session.FbLoggedIn()) {
                Intent i = new Intent(SplashActivity.this,
                        MainActivity.class);
                startActivity(i);
                finish();
                overridePendingTransition(R.anim.entry, R.anim.exit);
            } else {
                Intent i = new Intent(SplashActivity.this,
                        LoginActivity.class);
                startActivity(i);
                finish();
                overridePendingTransition(R.anim.entry, R.anim.exit);
            }

        }

    }, 3000);
}

最后,改变 onRequestPermissionsResult() 方法如下: -

@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    switch (requestCode) {
    case ALL_PERMISSIONS_RESULT:
        for (String perms : permissionsToRequest) {
            if (!hasPermission(perms)) {
                permissionsRejected.add(perms);
            }
        }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (permissionsRejected.size() > 0) {
                if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                    showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                    }
                                }
                            });
                    return;
                }
            }
            else {
               animation2();
               animation3();
               setUserLocation();   //After that start app
            }
        }
        else {
            animation2();
            animation3();
            setUserLocation();   //After that start app
        }
            break;
    }

}

因此,此解决方案首先遵循权限,然后是user-Location,然后是startApp。