我是java / android dev的新手,所以我的代码可能很笨。
我有一个使用谷歌地图的网站,我在网站上有一个按钮,使用firebase向特定设备发送推送cURL消息。我希望设备然后获取当前位置并更新我的数据库。
我使用MyFirebaseMessagingService和onMessageReceived来获取cURL消息并且一切正常,当我开始进入位置代码时,它会中断。我有各种错误,所以我尝试创建一个类来获取位置,然后在我的服务中调用该类的方法。
班级:
public class LocationMedium {
private FusedLocationProviderClient mFusedLocationClient;
private Context mContext;
public LocationMedium(Context context) {
mContext=context;
}
public void getLocation()
{
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//currently pointless
//return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener((Activity)mContext, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
Log.d("mytag", "2222");
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
double x = location.getLatitude();
double y = location.getLongitude();
Log.d("mytag1", String.valueOf(x));
Log.d("mytag2", String.valueOf(y));
String user = PreferenceManager.getDefaultSharedPreferences(mContext).getString("USERNAME", "none");
MyFirebaseInstanceIDService firebase = new MyFirebaseInstanceIDService();
firebase.onDeadline(user, x, y);
} else //no location found
{
String user = PreferenceManager.getDefaultSharedPreferences(mContext).getString("USERNAME", "none");
MyFirebaseInstanceIDService firebase = new MyFirebaseInstanceIDService();
firebase.onDeadline(user, 0, 0);
Log.d("mytag", "hmm");
}
}
});
//END OF LOCATION
Log.d("mytag", "theend");
}//end of run
}
我从MyFirebaseMessagingService
中调用它 if (Objects.equals(user, " location ")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
LocationMedium task = new LocationMedium(context);
task.getLocation();
}
});
}
我得到的错误是:
MyFirebaseMessagingService cannot be cast to android.app.Activity
它似乎就在这条线上:
mFusedLocationClient.getLastLocation()
我尝试从以下位置删除(Activity)位:
.addOnSuccessListener((Activity) mContext, new OnSuccessListener<Location>()
并将其更改为:
.addOnSuccessListener(mContext, new OnSuccessListener<Location>()
然后我收到错误:
Cannot resolve method 'addOnSuccessListener...'
也许我完全以错误的方式解决这个问题。任何帮助/建议将不胜感激。感谢。
答案 0 :(得分:0)
.addOnSuccessListener(mContext, new OnSuccessListener<Location>()
以此替换上面的代码,
.addOnSuccessListener(new OnSuccessListener<Location>()
为我工作。