应该在广播接收器(警报管理器)中使用什么上下文?
我已经尝试在服务中成功使用此代码,但是当我尝试在 AlarmService 中运行它时,我在 getApplicationContext() 和 myLocation.getLocation(this, locationResult) 中遇到错误;
我试过传递在服务中工作的上下文,消除了错误,但程序在运行时会崩溃。
LocationResult locationResult = new LocationResult(){
@Override
public void gotLocation(Location location){
Toast.makeText(getApplicationContext(), "Latitude: "+location.getLatitude()+"\n Longitude: "+location.getLongitude() , Toast.LENGTH_SHORT).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
错误:
toast :
未为类型 new MyLocation.LocationResult() 定义方法 getApplicationContext(){}
MyLocation 类型中的方法 getLocation(Context, MyLocation.LocationResult) 不适用于参数 (Alarm, MyLocation.LocationResult)
最佳答案
您可以将此函数保存在 MainActivity 以外的单独类文件中。
你可以通过这样做来解决这个问题
public static Context context = getApplicationContext();
在您的 Mainactivity 类中同时定义成员变量。然后你可以在 locationresult 类中使用 toast 消息中的上下文,如下所示
Toast.makeText(MainActivity.context, "Latitude: "+location.getLatitude()+"\n Longitude: "+location.getLongitude() , Toast.LENGTH_SHORT).show();
编辑:
1) 更好的方法是将上下文作为参数从您初始化位置类的 Activity 传递。
2) 如果您使用的是当前方法,请在显示 toast 消息之前为上下文添加空检查,以消除出现空异常的可能性。
关于java - Android 上下文问题 - 广播接收器(警报管理器)中应使用什么上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539025/