【问题标题】:getting gps data from service in background在后台从服务中获取 gps 数据
【发布时间】:2018-08-19 13:35:48
【问题描述】:

当我不使用我正在编程的应用程序时,我试图获取 gps 数据(速度)。 但总是当我关闭应用程序时,它会停止要求 gps 更新。现在我被告知,我必须使用一项服务。所以我做到了,但每次我接近应用程序的 ui 时它仍然停止要求更新。 这是我的服务代码:

package com.example.slartibartfast.kslordered;

public class BackroundService extends Service {

    private static float speed;

    //initializing the Location Manager and Listener
    LocationManager locationManager;
    LocationListener locationListener;

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

    @SuppressLint("MissingPermission")
    @Override
    public void onCreate() {
        //Instantiating the device manager an  listener
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //when the location changed

                Log.d("Location", ""+location);
                Log.d("Float Location", ""+ location.getLongitude() + "     " + location.getLatitude());
                Log.d("Speed", "    "+location.getSpeed());

                //initializing the variable speed with the speed number given by the LocationListener
                speed = location.getSpeed();

                //creating a broadcast reciever
                Intent intent = new Intent("speed_update");
                intent.putExtra("speed", speed);
                //sending speed to main activity
                sendBroadcast(intent);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {
                //if gps is disabled, this opens the gps settings
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        };
        locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
}

这里是我的主要活动:

package com.example.slartibartfast.kslordered;

public class MainActivity extends AppCompatActivity {

//initializing ui elements
TextView textviewSpeed;
Button button;

//initializing ui BroadcastReciever
private BroadcastReceiver broadcastReceiver;

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //instantiating the ui elements
    textviewSpeed = (TextView)findViewById(R.id.textview_speed);

    //checking if permission to use gps location is given
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 10);
        return;
    }else{

    }
    startService(new Intent(this, BackroundService.class));
}

@Override
protected void onResume() {
    super.onResume();
    //broadcast reciever gets speed from the backround service
    if (broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //speed get's set on the textview
                textviewSpeed.setText(""+ intent.getExtras().get("speed"));
            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("speed_update"));
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //asks for the gps user permission
    switch (requestCode){
        case 10:
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //(5000);
            }
    }
}

【问题讨论】:

    标签: android service gps


    【解决方案1】:

    我认为您需要在 OnStart 而不是 OnCreate 上添加代码

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //when the location changed
    
                Log.d("Location", ""+location);
                Log.d("Float Location", ""+ location.getLongitude() + "     " + location.getLatitude());
                Log.d("Speed", "    "+location.getSpeed());
    
                //initializing the variable speed with the speed number given by the LocationListener
                speed = location.getSpeed();
    
                //creating a broadcast reciever
                Intent intent = new Intent("speed_update");
                intent.putExtra("speed", speed);
                //sending speed to main activity
                sendBroadcast(intent);
    
            }
    
    
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
    
            }
    
    
            @Override
            public void onProviderEnabled(String s) {
    
            }
    
    
            @Override
            public void onProviderDisabled(String s) {
                //if gps is disabled, this opens the gps settings
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        };
        locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
        return START_STICKY;
    }
    

    【讨论】:

    • 我在onStart中推送了代码。仍然会随着 GPS 更新而停止。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多