2017-12-16 5 views
0

앱을 백그라운드에서 실행할 때 현재 위치를 얻으 려하므로 서비스를 사용합니다. 그러나 데이터가 백그라운드에서 변경되지 않으면 서비스가 작동하지 않습니다. 나는 그 문제를 알고 싶다. 다음은 앱의 코드입니다. 다음과 같은서비스를 통해 배경에 안드로이드 앱을 실행할 수 없습니다.

MainActivity :

.......... 

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 

......... 

<service android:name=".GoogleService" android:exported="false" android:enabled="true"/> 
</application> 

</manifest> 
을 따를

......... 
compile 'com.android.support:appcompat-v7:25.0.0' 
compile 'com.google.android.gms:play-services-location:10.0.1' 
compile 'com.android.support:multidex:1.0.0' 

AndroidManifest를에 따라

public class GoogleService extends Service implements LocationListener{ 

boolean isGPSEnable = false; 
boolean isNetworkEnable = false; 
double latitude,longitude; 
LocationManager locationManager; 
Location location; 
private Handler mHandler = new Handler(); 
private Timer mTimer = null; 
long notify_interval = 1000; 
public static String str_receiver = 
"com.findmyelderly.findmyelderly.receiver"; 
Intent intent; 




public GoogleService() { 

} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 

    mTimer = new Timer(); 
    mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval); 
    intent = new Intent(str_receiver); 
//  fn_getlocation(); 
} 

@Override 
public void onLocationChanged(Location location) { 

} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

private void fn_getlocation() { 
    locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); 
    isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

    if (!isGPSEnable && !isNetworkEnable) { 

    } else { 

     if (isNetworkEnable) { 
      location = null; 
      try { 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this); 
       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 

         Log.e("latitude", location.getLatitude() + ""); 
         Log.e("longitude", location.getLongitude() + ""); 

         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
         fn_update(location); 
        } 
       } 
      } catch (SecurityException e) { 
       e.printStackTrace(); 
      } 
     } 


      if (isGPSEnable) { 
       location = null; 
       try { 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this); 
        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          Log.e("latitude", location.getLatitude() + ""); 
          Log.e("longitude", location.getLongitude() + ""); 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
          fn_update(location); 
         } 
        } 
       } catch (SecurityException e) { 
        e.printStackTrace(); 
       } 
      } 


     } 

    } 

    private class TimerTaskToGetLocation extends TimerTask { 
     @Override 
     public void run() { 

      mHandler.post(new Runnable() { 
       @Override 
       public void run() { 
        fn_getlocation(); 
       } 
      }); 

     } 
    } 


private void fn_update(Location location){ 

    intent.putExtra("latutide",location.getLatitude()+""); 
    intent.putExtra("longitude",location.getLongitude()+""); 
    sendBroadcast(intent); 
} 


} 

build.gradle과 같이 다음과 같은

public class MainActivity extends Activity { 
Button btn_start; 
private static final int REQUEST_PERMISSIONS = 100; 
boolean boolean_permission; 
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality; 
SharedPreferences mPref; 
SharedPreferences.Editor medit; 
Double latitude,longitude; 
Geocoder geocoder; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btn_start = (Button) findViewById(R.id.btn_start); 
    tv_address = (TextView) findViewById(R.id.tv_address); 
    tv_latitude = (TextView) findViewById(R.id.tv_latitude); 
    tv_longitude = (TextView) findViewById(R.id.tv_longitude); 
    tv_area = (TextView)findViewById(R.id.tv_area); 
    tv_locality = (TextView)findViewById(R.id.tv_locality); 
    geocoder = new Geocoder(this, Locale.getDefault()); 
    mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    medit = mPref.edit(); 


    btn_start.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      if (boolean_permission) { 

       if (mPref.getString("service", "").matches("")) { 
        medit.putString("service", "service").commit(); 

        Intent intent = new Intent(getApplicationContext(), GoogleService.class); 
        startService(intent); 

       } else { 
        Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show(); 
       } 
      } else { 
       Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show(); 
      } 

     } 
    }); 

    fn_permission(); 
} 

private void fn_permission() { 
    if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { 

     if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) { 


     } else { 
      ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION 

        }, 
        REQUEST_PERMISSIONS); 

     } 
    } else { 
     boolean_permission = true; 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 

    switch (requestCode) { 
     case REQUEST_PERMISSIONS: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       boolean_permission = true; 

      } else { 
       Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show(); 

      } 
     } 
    } 
} 

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     latitude = Double.valueOf(intent.getStringExtra("latitude")); 
     longitude = Double.valueOf(intent.getStringExtra("longitude")); 

     List<Address> addresses = null; 

     try { 
      addresses = geocoder.getFromLocation(latitude, longitude, 1); 
      String cityName = addresses.get(0).getAddressLine(0); 
      String stateName = addresses.get(0).getAddressLine(1); 
      String countryName = addresses.get(0).getAddressLine(2); 

      tv_area.setText(addresses.get(0).getAdminArea()); 
      tv_locality.setText(stateName); 
      tv_address.setText(countryName); 



     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 


     tv_latitude.setText(latitude+""); 
     tv_longitude.setText(longitude+""); 
     tv_address.getText(); 


    } 
}; 

@Override 
protected void onResume() { 
    super.onResume(); 
    registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver)); 

} 

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


} 

서비스

나는 매우 혼란 스럽다.

답변

0

시도해 볼 수있는 한 가지 방법은 휴대 전화에서 앱의 권한을 확인하는 것입니다. 내 장치 (안드로이드 버전 6.0.1)로 "uses-permission android : name ="android.permission.ACCESS_FINE_LOCATION "/> 및 "uses-permission android : name = "android를 추가하는 것만으로는 충분하지 않습니다. 권한 >ACCESS_COARSE_LOCATION "/>" 을 입력하면 기기에서 직접 앱에 권한을 부여해야합니다.

설정하려면 앱> 'yourApp'> 권한으로 이동 한 다음 표시 줄을 그 앱의 위치를 ​​켜십시오.

저는 안드로이드 앱에 충분히 새로워서 귀하의 경우에 더 큰 문제가있을 수 있습니다. 어쨌든 시도할만한 가치가 있습니다.

관련 문제