Android 使用FCM发送位置坐标

Android 使用FCM发送位置坐标,android,firebase,firebase-realtime-database,firebase-cloud-messaging,Android,Firebase,Firebase Realtime Database,Firebase Cloud Messaging,我在两台android设备之间使用firebase制作了一个聊天应用程序,它工作正常,多个客户端可以登录到同一个房间并聊天。 我想在我的代码中添加一个gps活动,这样当一个用户发送gps这个词时,另一个用户会每隔5秒发送一次它的位置,只需继续发送。 这个想法是在收到的信息上加上一个条件,如果它带有“GPS”这个词,就继续发送位置信息。我如何用我的聊天代码做到这一点 主要活动: public class MainActivity extends AppCompatActivity { Ed

我在两台android设备之间使用firebase制作了一个聊天应用程序,它工作正常,多个客户端可以登录到同一个房间并聊天。 我想在我的代码中添加一个gps活动,这样当一个用户发送gps这个词时,另一个用户会每隔5秒发送一次它的位置,只需继续发送。 这个想法是在收到的信息上加上一个条件,如果它带有“GPS”这个词,就继续发送位置信息。我如何用我的聊天代码做到这一点

主要活动:

public class MainActivity extends AppCompatActivity {
    EditText roomname;
    Button join;
    ListView roomlist;
    ArrayList<String> roomarraylist; // to store rooms list
    ArrayAdapter<String>  roomadapter;

    DatabaseReference databaseReference;
    public String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        roomname=(EditText)findViewById(R.id.editText);
        join=(Button)findViewById(R.id.button2);

        roomlist=(ListView)findViewById(R.id.roomlistview);
        roomarraylist=new ArrayList<String>();
        roomadapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,roomarraylist);

        roomlist.setAdapter(roomadapter);

        databaseReference= FirebaseDatabase.getInstance().getReference().getRoot();

        request_username();
        join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String,Object> map=new HashMap<String, Object>();
                map.put(roomname.getText().toString(),"");
                databaseReference.updateChildren(map);
            }
        });
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterator iterator =dataSnapshot.getChildren().iterator();
                Set<String> set=new HashSet<String>();

                while (iterator.hasNext()){
                    // GET NAMES OF ALL ROOMS ONE BY ONE FROM  DATABASE
                    set.add((String) ( (DataSnapshot)iterator.next()).getKey());
                }
                roomarraylist.clear();
                roomarraylist.addAll(set);

                roomadapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        roomlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(MainActivity.this,Chat_room.class);
                intent.putExtra("Room_Name",((TextView)view).getText().toString());
                intent.putExtra("UserName",username);
                startActivity(intent);
            }
        });
    }

    private void request_username() {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("Please Enter your Name");
        final EditText edittext=new EditText(this);
        builder.setView(edittext);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                username=edittext.getText().toString();
                if(!TextUtils.isEmpty(username)){

                }
                else{
                    request_username();
                }
            }
        }).setNegativeButton("Quit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                request_username();
            }
        });

        builder.show();
    }
}

这是太晚的回答,但无论如何我会在这里提到它

如果您订阅了一个主题(我的假设),那么您只需要向该主题发送一个POST请求

下面是我为实现您所要求的相同功能而编写的代码

URL fireBaseUrl = new URL("https://fcm.googleapis.com/fcm/send");
            HttpsURLConnection urlConnection = (HttpsURLConnection) fireBaseUrl.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.addRequestProperty("Content-Type", "application/json");
            urlConnection.addRequestProperty("Authorization", "key=" + NetworkUtils.SERVER_KEY); // Paste your server key here
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            JSONObject notification = new JSONObject()
                    .put("to", "/topics/skm") // Your topic here
                    .put("data", new JSONObject()
                            .put("latitude", longitude)
                            .put("longitude", latitude));

            OutputStreamWriter oStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
            String requestString = notification.toString();
            Log.d("JSON REQUEST", requestString);

            oStreamWriter.write(requestString);
            oStreamWriter.close();

            int status = urlConnection.getResponseCode();
            Log.d("STATUS CODE", status + "");


            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder responseBuilder = new StringBuilder();
            String readLine;

            while ((readLine = in.readLine()) != null) {
                responseBuilder.append(readLine);
            }

            response = responseBuilder.toString();

            Log.d("RESPONSE", response);
就这样。我希望您能够在客户端接收Lat/Long

public class Gps extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    TextView x;
    TextView y;
    LocationRequest LR;
    private GoogleApiClient GAC;
    String lat;
    String Lon;
    //public  String lat="Latitude";
    //public  String lon="Longitude";

    @Override
    public void onConnected(Bundle connectionHint) {
        createLocationRequest();
        startLocationUpdates();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location Location = LocationServices.FusedLocationApi.getLastLocation(GAC);
        if (Location != null) {
            Double Lat = Location.getLatitude();
            Double lon = Location.getLongitude();
            x = (TextView) findViewById(R.id.textView);
            y = (TextView) findViewById(R.id.textView2);
            x.setText("Ltitude is " + String.valueOf(Lat));
            y.setText("Longitude is " + String.valueOf(lon));

        }


    }


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

    @Override

    protected void onStop() {
        GAC.disconnect();
        super.onStop();
    }

    @Override
    public void onConnectionSuspended(int cause) {
        Toast.makeText(this, "the connection suspended", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Toast.makeText(this, "the connection failed", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onLocationChanged(Location location) {
        x = (TextView) findViewById(R.id.textView);
        y = (TextView) findViewById(R.id.textView2);
        x.setText("latitude is " + String.valueOf(location.getLatitude()));
        y.setText("longitude is " + String.valueOf(location.getLongitude()));
    }

    protected void createLocationRequest() {
        LR = new LocationRequest();
        LR.setInterval(5000);
        LR.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void startLocationUpdates() {

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                GAC, LR, (this));

    }


    protected void build_GAC() {
        GAC = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

    }



    @Override
    protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        build_GAC();
}
}
URL fireBaseUrl = new URL("https://fcm.googleapis.com/fcm/send");
            HttpsURLConnection urlConnection = (HttpsURLConnection) fireBaseUrl.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.addRequestProperty("Content-Type", "application/json");
            urlConnection.addRequestProperty("Authorization", "key=" + NetworkUtils.SERVER_KEY); // Paste your server key here
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);

            JSONObject notification = new JSONObject()
                    .put("to", "/topics/skm") // Your topic here
                    .put("data", new JSONObject()
                            .put("latitude", longitude)
                            .put("longitude", latitude));

            OutputStreamWriter oStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
            String requestString = notification.toString();
            Log.d("JSON REQUEST", requestString);

            oStreamWriter.write(requestString);
            oStreamWriter.close();

            int status = urlConnection.getResponseCode();
            Log.d("STATUS CODE", status + "");


            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder responseBuilder = new StringBuilder();
            String readLine;

            while ((readLine = in.readLine()) != null) {
                responseBuilder.append(readLine);
            }

            response = responseBuilder.toString();

            Log.d("RESPONSE", response);