简体   繁体   中英

Android - Starting Service in Intent

I'm trying to develop my first Android Application. My goal is to create a small fitness app. Currently i'm trying to get the users location via an IntentService that i wrote. I'm using the LocationManager for this and sending my data over an broadcast.

In the fragment i'm using a broadcastreciever to display the actual GPS coords.

Unfortunately i'm not getting the data after i gave the app the required permissions.

Here are the files: GpsFragment.java

package ch.brad.fitit.fititreloaded;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;


public class GpsFragment extends Fragment {

  private Button startButton, stopButton;
  private TextView latLngText, speedLabel;
  private BroadcastReceiver broadcastReceiver;

  // private FileStorage fs;
  private OnFragmentInteractionListener mListener;

  public GpsFragment() {
    // Required empty public constructor
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  private void enable_buttons(){
    Log.d("GPS", "enabling buttons");
    startButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Log.d("Action", "Start clicked");

        getActivity().startService(new Intent(getActivity(), GPS_Service.class));
      }
    });

    stopButton.setOnClickListener(new View.OnClickListener(){
      @Override
      public void onClick(View view){
        Log.d("Action", "Stop clicked");

        getActivity().stopService(new Intent(getActivity(), GPS_Service.class));
      }
    });
  }

  private boolean runtime_permissions(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.INTERNET
        }, 100);
        return true;
      }
    }
    return false;
  }

  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 100){
      if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
        enable_buttons();
      } else {
        runtime_permissions();
      }
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_gps, container, false);

    startButton = (Button) v.findViewById(R.id.startButton);
    stopButton = (Button) v.findViewById(R.id.stopButton);

    // latLngText = (TextView) fl.findViewById(R.id.latLngText);
    // speedLabel = (TextView) fl.findViewById(R.id.speedLabel);

    if(!runtime_permissions()) enable_buttons();


    // getActivity().registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

    if(broadcastReceiver == null){
      broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          String coordString = (String) intent.getExtras().get("coordinates");
          String speedString = (String) intent.getExtras().get("speed");

          Log.d("GPS-DATA", coordString + " " + speedString);

          // latLngText.append("\n" + coordString);
          // speedLabel.append("\n" + speedString + " m/s");
          // fs.writeData(coordString, getApplicationContext());
        }
      };
    }
    // Inflate the layout for this fragment
    return v;
  }

  // TODO: Rename method, update argument and hook method into UI event
  public void onButtonPressed(Uri uri) {
    if (mListener != null) {
      mListener.onFragmentInteraction(uri);
    }
  }

  @Override
  public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
      mListener = (OnFragmentInteractionListener) context;
    } else {
      throw new RuntimeException(context.toString()
          + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  public void onDestroy(){
    super.onDestroy();
    if(broadcastReceiver != null) getActivity().unregisterReceiver(broadcastReceiver);
  }

  public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
  }
}

GPS_Service.java

package ch.brad.fitit.fititreloaded;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

public class GPS_Service extends IntentService {
  private LocationListener listener;
  private LocationManager locationManager;
  private double oldLat;
  private double oldLng;
  private boolean firstSpeedCalculation = true;

  private static int REFRESH_TIME = 1000;

  public GPS_Service() { super("GPSService"); }

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

  @Override
  protected void onHandleIntent(@Nullable Intent intent) { }

  @SuppressLint("MissingPermission")
  @Override
  public void onCreate() {
    super.onCreate();
    Log.d("service", "Starting Service");

    listener = new LocationListener() {
      @Override
      public void onLocationChanged(Location location) {
        Intent i = new Intent("location_update");
        String speed = calcucalteSpeed(location.getLatitude(), location.getLongitude());
        i.putExtra("coordinates", location.getLatitude() + " " + location.getLongitude());
        i.putExtra("speed", speed);

        Log.d("service", location.getLatitude() + " " + location.getLongitude());

        sendBroadcast(i);
      }

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

      @Override
      public void onProviderEnabled(String s) {}

      @Override
      public void onProviderDisabled(String s) {
        Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
      }
    };

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, REFRESH_TIME,0, listener);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if(locationManager != null){
      locationManager.removeUpdates(listener);
    }
  }
}

Do you know where the problem is? Do I misunderstand something? If you need more infos, let me know...

You're not registering your BroadcastReceiver. You have a register line, but it's commented.

Change:

// getActivity().registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

if(broadcastReceiver == null){
  broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      String coordString = (String) intent.getExtras().get("coordinates");
      String speedString = (String) intent.getExtras().get("speed");

      Log.d("GPS-DATA", coordString + " " + speedString);

      // latLngText.append("\n" + coordString);
      // speedLabel.append("\n" + speedString + " m/s");
      // fs.writeData(coordString, getApplicationContext());
    }
  };
}

To:

if(broadcastReceiver == null){
  broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      String coordString = (String) intent.getExtras().get("coordinates");
      String speedString = (String) intent.getExtras().get("speed");

      Log.d("GPS-DATA", coordString + " " + speedString);

      // latLngText.append("\n" + coordString);
      // speedLabel.append("\n" + speedString + " m/s");
      // fs.writeData(coordString, getApplicationContext());
    }
  };
}

getActivity().registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

For any internal broadcasts, you should also consider using LocalBroadcastManager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM