有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在单独的类中使用getContentResolver()

我有一个从broadcastReceiver扩展而来的类,它给我提供GPS坐标。我想显示手机的序列号及其坐标

public class AlarmReceiver extends BroadcastReceiver{

long time = 10 * 1000; 

@Override
public void onReceive(final Context context, Intent intent) {

    LocationManager locationManager = (LocationManager)context
            .getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();

    String provider = locationManager.getBestProvider(criteria, true);

    locationManager.requestLocationUpdates(provider, time, minDistance, locationListener);

    Location location = locationManager.getLastKnownLocation(provider);

    String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL :        Secure.getString(getContentResolver(), Secure.ANDROID_ID);   // returns device id of phone              

    String Text = "Latitude = " + location.getLatitude() +" Longitude = " location.getLongitude(); 

        Toast.makeText(context, Text, Toast.LENGTH_SHORT).show(); 

      } catch (Exception e) {
          Toast.makeText(context, "SMS faild, please try again.",
         Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
   }

    LocationListener locationListener = new LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

}

为了获取设备序列号,我使用了以下代码,但它显示了一个错误,即getContentResolver()未定义。我已经搜索了解决方案,并尝试了getActivity()和getApplicationContext(),但这对我不起作用

String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL :       Secure.getString(getContentResolver(), Secure.ANDROID_ID);   // returns device id of phone 

共 (2) 个答案

  1. # 1 楼答案

    嗯,应该是:

    context.getContentResolver()
    

    因为ContentResolver属于Context,并且Context通过回调传递

  2. # 2 楼答案

    只需传递Context并用context.getContentResolver().调用它