Pregunta

Hi I have a service in which I find the user location co-ordinates. This service is started in onCreate in my MainActivity. however until it finds the values as I know GPS can take some time to find the co-ordinates the screen is black. I have created a splash screen which I would like to show but I am not sure on how to implement. My code will explain more:

My service:

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 ( Only the relevant parts):

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

    };
¿Fue útil?

Solución

Check my answer here: Android SplashScreen

Basically creating a theme background will deal with the black screen till you set the content.

Otros consejos

Create a splash_screen activity. Set it as start-up activity.

In this splash_screen activity's onCreate() u can start a service to get location update.

Once u r done with location update, start ur MainAcitivity.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();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top