我在两个移动设备之间使用firebase创建了一个聊天应用程序然后我创建了一个按钮,使用Google API客户端发送设备的位置,但它仍然返回null虽然我在另一个活动中尝试了它并且它工作正常。 ChatRoom ::
public class Chat_room extends Activity implements ConnectionCallbacks,OnConnectionFailedListener, LocationListener {
Button btnsend, btnGps;
TextView recievedmsg, txtgps;
EditText editmsg;
DatabaseReference rootRoomName;
String roomname;
String username;
private String chatusername;
private String chatmessage;
String Response;
private GoogleApiClient GAC;
LocationRequest LR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
build_GAC();
setContentView(R.layout.activity_chat_room);
btnsend = (Button) findViewById(R.id.btnsend);
btnGps = (Button) findViewById(R.id.btnGps);
recievedmsg = (TextView) findViewById(R.id.recievedmsg);
editmsg = (EditText) findViewById(R.id.editmsg);
txtgps = (TextView) findViewById(R.id.txtgps);
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",Response);
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");
}
protected void build_GAC(){
GAC =new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
if (GAC != null) {
GAC.connect();
}
}
@Override
protected void onStop() {
GAC.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle connectionHint) {
createLocationRequest();
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location Location = LocationServices.FusedLocationApi.getLastLocation(GAC);
if (Location != null) {
Double Lat = Location.getLatitude();
Double lon = Location.getLongitude();
Response=("Ltitude is " + String.valueOf(Lat) + "\n" + "Longitude is " + String.valueOf(lon));
}
}
protected void createLocationRequest() {
LR = new LocationRequest();
LR.setInterval(2000);
LR.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(this, "the connection suspended", Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "the connection failed", Toast.LENGTH_LONG).show();
}
@Override
public void onLocationChanged(Location location) {
Response=("Ltitude is " + String.valueOf(location.getLatitude()) + "\n \n" + "Longitude is " + String.valueOf(location.getLongitude()));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
主要活动::
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();
}
}
答案 0 :(得分:0)
如果您使用的设备的目标数超过6.0,那么您还没有提到您正在使用哪种设备,那么考虑到以下代码就无法使用
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
如果在您的应用中授予了权限,我无法看到用于发出位置请求的代码,那么它将直接返回而不会发出位置请求。
考虑以下链接 http://javapapers.com/android/android-location-fused-provider/