2016-06-04 1 views
0

이것은 내가 작성한 코드이며 버튼 클릭으로 사용자 미술의 일정한 간격의 현재 위치를 보여주는 간단한 활동입니다. 나는 버튼을 클릭 할 때 사용자의 현재 위치를 가져 오는 서비스를 시작하지만 그렇게 할 수 없도록 서비스를 만들고 싶습니다. 어떤 사람이 저를 도울 수 있습니까? 이것은 MainActivity.java의 코드입니다. 당신은 불행하게도 작동하지 않았다, 당신에게서 몇 가지 가장 유망한 시험을 추가하는 경우간단한 안드로이드 앱에 새 서비스를 추가하는 데 도움이 필요합니다.

package com.maps.saury.location; 


    import android.app.Activity; 
    import android.app.Service; 
    import android.content.Intent; 
    import android.location.Location; 
    import android.os.Bundle; 
    import android.os.IBinder; 
    import android.support.annotation.Nullable; 
    import android.util.Log; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.TextView; 
    import android.widget.Toast; 

    import com.google.android.gms.common.ConnectionResult; 
    import com.google.android.gms.common.GooglePlayServicesUtil; 
    import com.google.android.gms.common.api.GoogleApiClient; 
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
    import com.google.android.gms.location.LocationListener; 
    import com.google.android.gms.location.LocationRequest; 
    import com.google.android.gms.location.LocationServices; 

    public class MainActivity extends Activity implements ConnectionCallbacks, 
      OnConnectionFailedListener, LocationListener { 
     BGTask bgtask=new BGTask(this); 
     // LogCat tag 
     private static final String TAG = MainActivity.class.getSimpleName(); 

     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 

     private Location mLastLocation; 

     // Google client to interact with Google API 
     private GoogleApiClient mGoogleApiClient; 

     // boolean flag to toggle periodic location updates 
     private boolean mRequestingLocationUpdates = false; 

     private LocationRequest mLocationRequest; 

     // Location updates intervals in sec 
     private static int UPDATE_INTERVAL = 100; // 10 sec 
     private static int FATEST_INTERVAL = 100; // 5 sec 
     private static int DISPLACEMENT = 0; // 10 meters 

     // UI elements 
     private TextView lblLocation; 
     private Button btnShowLocation, btnStartLocationUpdates; 

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

      lblLocation = (TextView) findViewById(R.id.lblLocation); 
      btnShowLocation = (Button) findViewById(R.id.btnShowLocation); 
      btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates); 

      // First we need to check availability of play services 
      if (checkPlayServices()) { 

       // Building the GoogleApi client 
       buildGoogleApiClient(); 

       createLocationRequest(); 
      } 

      // Show location button click listener 
      btnShowLocation.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        displayLocation(); 
       } 
      }); 

      // Toggling the periodic location updates 
      btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        togglePeriodicLocationUpdates(); 
       } 
      }); 

     } 

     @Override 
     protected void onStart() { 
      super.onStart(); 
      if (mGoogleApiClient != null) { 
       mGoogleApiClient.connect(); 
      } 
     } 

     @Override 
     protected void onResume() { 
      super.onResume(); 

      checkPlayServices(); 

      // Resuming the periodic location updates 
      if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
       startLocationUpdates(); 
      } 
     } 

     @Override 
     protected void onStop() { 
      super.onStop(); 
      if (mGoogleApiClient.isConnected()) { 
       mGoogleApiClient.disconnect(); 
      } 
     } 

     @Override 
     protected void onPause() { 
      super.onPause(); 
      stopLocationUpdates(); 
     } 

     /** 
     * Method to display the location on UI 
     * */ 
     private void displayLocation() { 

      mLastLocation = LocationServices.FusedLocationApi 
        .getLastLocation(mGoogleApiClient); 

      if (mLastLocation != null) { 
       double latitude = mLastLocation.getLatitude(); 
       double longitude = mLastLocation.getLongitude(); 

       lblLocation.setText(latitude + ", " + longitude); 
       BGTask bgtask=new BGTask(this); 
       bgtask.execute(Double.toString(latitude),Double.toString(longitude)); 

      } else { 

       lblLocation 
         .setText("(Couldn't get the location. Make sure location is enabled on the device)"); 
      } 
     } 

     /** 
     * Method to toggle periodic location updates 
     * */ 
     private void togglePeriodicLocationUpdates() { 
      if (!mRequestingLocationUpdates) { 
       // Changing the button text 
       btnStartLocationUpdates 
         .setText(getString(R.string.btn_stop_location_updates)); 

       mRequestingLocationUpdates = true; 

       // Starting the location updates 
       startLocationUpdates(); 

       Log.d(TAG, "Periodic location updates started!"); 

      } else { 
       // Changing the button text 
       btnStartLocationUpdates 
         .setText(getString(R.string.btn_start_location_updates)); 

       mRequestingLocationUpdates = false; 

       // Stopping the location updates 
       stopLocationUpdates(); 

       Log.d(TAG, "Periodic location updates stopped!"); 
      } 
     } 

     /** 
     * Creating google api client object 
     * */ 
     protected synchronized void buildGoogleApiClient() { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(LocationServices.API).build(); 
     } 

     /** 
     * Creating location request object 
     * */ 
     protected void createLocationRequest() { 
      mLocationRequest = new LocationRequest(); 
      mLocationRequest.setInterval(UPDATE_INTERVAL); 
      mLocationRequest.setFastestInterval(FATEST_INTERVAL); 
      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
      mLocationRequest.setSmallestDisplacement(DISPLACEMENT); 
     } 

     /** 
     * Method to verify google play services on the device 
     * */ 
     private boolean checkPlayServices() { 
      int resultCode = GooglePlayServicesUtil 
        .isGooglePlayServicesAvailable(this); 
      if (resultCode != ConnectionResult.SUCCESS) { 
       if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
        GooglePlayServicesUtil.getErrorDialog(resultCode, this, 
          PLAY_SERVICES_RESOLUTION_REQUEST).show(); 
       } else { 
        Toast.makeText(getApplicationContext(), 
          "This device is not supported.", Toast.LENGTH_LONG) 
          .show(); 
        finish(); 
       } 
       return false; 
      } 
      return true; 
     } 

     /** 
     * Starting the location updates 
     * */ 
     protected void startLocationUpdates() { 

     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 

     } 

     /** 
     * Stopping location updates 
     */ 
     protected void stopLocationUpdates() { 
      LocationServices.FusedLocationApi.removeLocationUpdates(
        mGoogleApiClient, this); 
     } 

     /** 
     * Google api callback methods 
     */ 
     @Override 
     public void onConnectionFailed(ConnectionResult result) { 
      Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " 
        + result.getErrorCode()); 
     } 

     @Override 
     public void onConnected(Bundle arg0) { 

      // Once connected with google api, get the location 
      displayLocation(); 

      if (mRequestingLocationUpdates) { 
       startLocationUpdates(); 
      } 
     } 

     @Override 
     public void onConnectionSuspended(int arg0) { 
      mGoogleApiClient.connect(); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
      // Assign the new location 
      mLastLocation = location; 


      Toast.makeText(getApplicationContext(), "Locatn changed!", 
        Toast.LENGTH_SHORT).show(); 

      // Displaying the new location on UI 
      displayLocation(); 
     } 


    } 

이 내 Activity_Main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/view_bg" 
    android:gravity="center_horizontal" 
    android:orientation="vertical" > 

    <ImageView 
     android:layout_width="60dp" 
     android:layout_height="60dp" 
     android:layout_marginTop="60dp" 
     android:src="@drawable/marker" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="25dp" 
     android:text="@string/lbl_you_are_at" 
     android:textColor="@color/white" 
     android:textSize="25dp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/lblLocation" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:gravity="center_horizontal" 
     android:padding="15dp" 
     android:textColor="@color/white" 
     android:textSize="16dp" /> 

    <Button 
     android:id="@+id/btnShowLocation" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="40dp" 
     android:background="@color/btn_bg" 
     android:paddingLeft="20dp" 
     android:paddingRight="20dp" 
     android:text="@string/btn_get_location" 
     android:textColor="@color/white" /> 

    <Button 
     android:id="@+id/btnLocationUpdates" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="60dp" 
     android:background="@color/btn_bg" 
     android:paddingLeft="20dp" 
     android:paddingRight="20dp" 
     android:text="@string/btn_start_location_updates" 
     android:textColor="@color/white" /> 

</LinearLayout> 
+0

, 나는 확실히 사람들이보다 쉽게 ​​도움을 찾을 것입니다 . – Dilettant

답변

0
First Check your Manifest.xml and check Internet permission. 

<permission 
     android:name="com.hamms.cabsystem.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

Second Check google Map Api Meta data. 
    <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="AIzaSyBBGHOC13C00ew4xKD7kyei0M3bul8093s" /> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 

Then, Create on ServiceClass like this and start Service on click of button. 


btn_save.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

      startService(new Intent(this,MyService.class)); 

} 
} 

public class MyService extend Service{ 

onstartCommand(){ 

Intent i = new Intent(youraction); 
sendBroadCast(i); 

} 

In Myservice onStartCommand Method Send OneBraodcast which is update your location. 

Register Brodcast Receiver in Manifest,xml 
<receiver android:name="MyBroadCast"></receiver> 

public class MyBroadCast extend BrodcastReciver{ 

// here onRecive Method you upadate your location. 
// do something here // 

} 
+0

내가 아는 전부는 mainactivity.java에 너무 많은 코드가있어서 서비스 클래스 안에 무엇을 넣을 지 결정할 수 없습니다. –

관련 문제