显示开机画面,而不是黑屏,而定位用户Android



嗨,我有一个服务,我找到用户的位置坐标。这个服务在我的MainActivity的onCreate中启动。然而,直到它找到值,因为我知道GPS可以花一些时间找到坐标,屏幕是黑色的。我已经创建了一个启动屏幕,我想显示,但我不确定如何实现。我的代码将解释更多:

我的服务:

public class LocationService extends Service implements
 GooglePlayServicesClient.ConnectionCallbacks,
 GooglePlayServicesClient.OnConnectionFailedListener,
    LocationListener {
    public static double curlat;
    public static double curlong;
    IBinder mBinder = new LocalBinder();
   private LocationClient mLocationClient;
   private LocationRequest mLocationRequest;
   // Flag that indicates if a request is underway.
   private boolean mInProgress;
   public static final String BROADCAST_ACTION =  "com.example.fusedlocation.displayevent";
   Intent intent;
   private Boolean servicesAvailable = false;
   public class LocalBinder extends Binder {
    public LocationService getServerInstance() {
        return LocationService.this;
    }
   }
   @Override
    public void onCreate() {
       super.onCreate();

       intent = new Intent(BROADCAST_ACTION);
       mInProgress = false;
       // Create the LocationRequest object
       mLocationRequest = LocationRequest.create();
       // Use high accuracy
       mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
       // Set the update interval to 5 seconds
       mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
       // Set the fastest update interval to 1 second
       mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
       servicesAvailable = servicesConnected();
       /*
        * Create a new location client, using the enclosing class to
        * handle callbacks.
        */
       mLocationClient = new LocationClient(this, this, this);

   }
   private boolean servicesConnected() {
       // Check that Google Play services is available
       int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
       // If Google Play services is available
       if (ConnectionResult.SUCCESS == resultCode) {
           return true;
       } else {
           return false;
       }
   }
   public int onStartCommand (Intent intent, int flags, int startId)
   {
       super.onStartCommand(intent, flags, startId);
       if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;
       setUpLocationClientIfNeeded();
       if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
       {
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
        mInProgress = true;
        mLocationClient.connect();
       }
       return START_STICKY;
   }
    /*
    * Create a new location client, using the enclosing class to
    * handle callbacks.
    */
   private void setUpLocationClientIfNeeded()
   {
    if(mLocationClient == null) 
           mLocationClient = new LocationClient(this, this, this);
   }
   // Define the callback method that receives location updates
   @Override
   public void onLocationChanged(android.location.Location location) {
       // Report to the UI that the location was updated
       String msg = Double.toString(location.getLatitude()) + "," +
               Double.toString(location.getLongitude());
       Log.d("debug", msg);
       curlat = location.getLatitude();
       curlong = location.getLongitude();
       // Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
       appendLog(msg, Constants.LOCATION_FILE);
       intent.putExtra("Latitude", location.getLatitude());
       intent.putExtra("Longitude", location.getLongitude());
       sendBroadcast(intent, null);
   }
   @Override
   public IBinder onBind(Intent intent) {
    return mBinder;
   }
   public String getTime() {
    SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return mDateFormat.format(new Date());
   }
   public void appendLog(String text, String filename)
   {       
      File logFile = new File(filename);
      if (!logFile.exists())
      {
         try
         {
            logFile.createNewFile();
         } 
         catch (IOException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      try
      {
         //BufferedWriter for performance, true to set append to file flag
         BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
         buf.append(text);
         buf.newLine();
         buf.close();
      }
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   @Override
   public void onDestroy(){
       // Turn off the request flag
       mInProgress = false;
       if(servicesAvailable && mLocationClient != null) {
            mLocationClient.removeLocationUpdates(this);
            // Destroy the current location client
            mLocationClient = null;
       }
       // Display the connection status
       // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
       super.onDestroy();  
   }
   /*
    * Called by Location Services when the request to connect the
    * client finishes successfully. At this point, you can
    * request the current location or start periodic updates
    */
   @Override
   public void onConnected(Bundle bundle) {
       // Request location updates using static settings
       mLocationClient.requestLocationUpdates(mLocationRequest, this);
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Connected", Constants.LOG_FILE);
   }

   /*
    * Called by Location Services if the connection to the
    * location client drops because of an error.
    */
   @Override
   public void onDisconnected() {
       // Turn off the request flag
       mInProgress = false;
       // Destroy the current location client
       mLocationClient = null;
       // Display the connection status
       // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
   }
   /*
    * Called by Location Services if the attempt to
    * Location Services fails.
    */
   @Override
   public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;
       /*
        * Google Play services can resolve some errors it detects.
        * If the error has a resolution, try sending an Intent to
        * start a Google Play services activity that can resolve
        * error.
        */
       if (connectionResult.hasResolution()) {
       // If no resolution is available, display an error dialog
       } else {
       }
   }   
}

MainActivity(仅相关部分):

public class MainActivity extends Activity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener{
    // Google Map & markers
    private GoogleMap googleMap;
    private Circle mCircle;
    private Marker mMarker;
    double radiusInMeters;
    long start_time, countUp, timeDialogShown = 0;
    double latitude, longitude, startLongitude, startLatitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Setting the layout
        setContentView(R.layout.activity_main);
        try {
            // Loading map
            initilizeMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
        startService(new Intent(this, LocationService.class));
    } // end onCreate
    //Checking the latest location updates
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
             latitude = extras.getDouble("Latitude");
             longitude = extras.getDouble("Longitude");
             LatLng latLng = new LatLng(latitude, longitude);
            if (mCircle == null || mMarker == null) {
                drawMarkerWithCircle(latLng);
            } else {
                updateMarkerWithCircle(latLng);
            }
            getDistance();
            //Getting the current weather conditions
            //if (condDescr.getText().equals(" ")){
            //  getWeatherConditions();
            //}
            //Check if the user has breached the Geofence boundaries
            checkBoundaries();
            }
    };

查看我的答案:Android SplashScreen

基本上创建一个主题背景将处理黑屏,直到你设置内容。

创建splash_screen活动。设置为启动活动

在splash_screen活动的onCreate()中,你可以启动一个服务来获取位置更新。

完成位置更新后,启动mainactivity .class。

protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen_layout);
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() { 
        // start the service  to get location update
        try {
             Thread.sleep(5000);
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        // start the main activity
    }
});
t1.start();
}

最新更新