使用FCM发送位置坐标

时间:2017-05-04 17:37:57

标签: android firebase firebase-realtime-database firebase-cloud-messaging

我在两个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();
    }
}

Chat_room类::

public class Chat_room extends AppCompatActivity {

    Button btnsend;
    TextView recievedmsg;
    EditText editmsg;

    DatabaseReference rootRoomName;

    String roomname;
    String username;
    private String chatusername;
    private String chatmessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room);
        btnsend=(Button)findViewById(R.id.btnsend);
        recievedmsg=(TextView)findViewById(R.id.recievedmsg);
        editmsg=(EditText)findViewById(R.id.editmsg);

        roomname=getIntent().getExtras().get("Room_Name").toString();
        username=getIntent().getExtras().get("UserName").toString();

        setTitle(roomname);
        rootRoomName= FirebaseDatabase.getInstance().getReference().getRoot().child(roomname);

        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatabaseReference childRoot=rootRoomName.push();
                Map<String,Object> map=new HashMap<String, Object>();

                map.put("Name",username);
                map.put("message",editmsg.getText().toString());

                childRoot.updateChildren(map);

            }
        });

        rootRoomName.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                update_message(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                update_message(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void update_message(DataSnapshot dataSnapshot) {
        chatusername=(String)dataSnapshot.child("Name").getValue();
        chatmessage=(String)dataSnapshot.child("message").getValue();

        recievedmsg.append(chatusername + ":" + chatmessage + "\n\n");
    }
}

GPS活动::

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();
}
}

1 个答案:

答案 0 :(得分:0)

这太迟了,但无论如何我会在这里提到它。

如果您订阅了主题(我的假设),那么您只需要向该主题发送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。