0

複数のクライアントが同じ部屋にサインインしてチャットできるうえで、2台のアンドロイドデバイス間でfirebaseを使用してチャットアプリケーションを作成しました。 私のコードにgpsアクティビティを追加して、あるユーザがgpsという単語を送信すると、他のユーザは5秒ごとにその場所を送信し、そのまま送信します。 それは言葉「GPS」私は私のチャットコードFCMを使用して位置座標を送信する

主な活動::

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

答えて

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を受け取れることを願っています。

関連する問題