【发布时间】:2019-02-15 23:07:27
【问题描述】:
此代码过去在旧的 android 版本上运行良好。当我用最新的 Android Studio 更新它时,它不再工作了。
我正在尝试将一个简单的字符串从我的一个类发送到主要活动。
我在清单中声明接收者...
<receiver android:name="com.domain.appname.MainActivity$MyReceiver">
<intent-filter>
<action android:name="MY_ACTION"/>
</intent-filter>
</receiver>
尝试使用意图发送广播时。这是检测到位置已更改的时间
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location)
{
addStats("onLocationChanged - "+mLastLocation.getLatitude()+" "+mLastLocation.getLongitude()+" "+mLastLocation.getAccuracy()+" "+mLastLocation.getSpeed());
mLastLocation.set(location);
//send latitude, longitude and accuracy as broadcast to main activity
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", mLastLocation.getLatitude()+" "+mLastLocation.getLongitude()+" "+mLastLocation.getAccuracy()+" "+mLastLocation.getSpeed());
sendBroadcast(intent);
addStats("after sendBroadcast");
}
@Override
public void onProviderDisabled(String provider){}
@Override
public void onProviderEnabled(String provider){}
@Override
public void onStatusChanged(String provider, int status, Bundle extras){}
}
其中的 addStats 行仅用于调试,它们都会触发。即,我看到它检测到新的 long/lat 的统计信息,并且我收到“after sendBroadcast”消息,所以看起来该代码正在发送(或尝试发送)广播。
现在在我的主要活动中,我将它作为接收者...
//receives the broadcasts from the MyLocationService service
public static class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
addStats("inside onReceive");
String datapassed = arg1.getStringExtra("DATAPASSED");
}
}
这永远不会被触发。我从来没有看到“inside onReceive”消息。
有什么我可能遗漏的想法吗?经历了很多 stackoverflow 和谷歌的结果,以上似乎是我需要做的。正如我所说,它曾经运行良好(可能是 Android 26 版),但我正试图让这个应用程序在较新的操作系统版本上运行。
【问题讨论】: