java - Android Intent.getStringExtra() 在 Broadcastreceiver 中返回 null

标签 java android android-intent service nullpointerexception

我制作了一个服务,它在位置更改后发出 Intent 并将位置数据放入其中。

intent.putExtra("Latitude", String.valueOf(loc.getLatitude())); //Double
            intent.putExtra("Longitude", String.valueOf(loc.getLongitude())); //Double
            intent.putExtra("Provider", loc.getProvider()); //String
            intent.putExtra("Altitude", loc.getAltitude());//Double
            intent.putExtra("Accuracy", loc.getAccuracy()); //float
            intent.putExtra("Speed", loc.getSpeed()); //float

现在,我有一个 Broadcastreceiver,它每 30 秒触发一次,用于将信息发布到服务器。但是,当我尝试获取 Intent 时:

        Intent myIntent = new Intent(context, GPSService.class); //GPSService is the service
        String lat = (String) myIntent.getExtras().get("Latitude");
        String longi = (String) myIntent.getExtras().get("Longitude");

我得到一个NullPointerException

Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference

这是为什么呢?我检查了其他解决方案:有人说要检查我是否将正确的 Dateformat 放入 Intent 中(在本例中是字符串),我这样做了,有人说要使用 getIntent().getExtras().getString("aKey"); 我也试过了,正如你在上面看到的那样,但我仍然从字符串中得到 null。

将它传递给 broadcastreceiver 时肯定存在一些问题,因为我在执行 intent.putExtra() 操作后记录了这些值,它们肯定不为空。

编辑:

GPS服务:

    package com.dandddeveloper.alarmisto;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class GPSService extends Service
{
    public static final String BROADCAST_ACTION = "Hello World";
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;

    Intent intent;
    int counter = 0;

    @Override
    public void onCreate()
    {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }



    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }



    @Override
    public void onDestroy() {
        // handler.removeCallbacks(sendUpdatesToUI);
        super.onDestroy();
        Log.v("STOP_SERVICE", "DONE");
        locationManager.removeUpdates(listener);
    }

    public static Thread performOnBackgroundThread(final Runnable runnable) {
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {

                }
            }
        };
        t.start();
        return t;
    }




    public class MyLocationListener implements LocationListener
    {

        public void onLocationChanged(final Location loc)
        {
            Log.i("***********************", "Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                loc.getLatitude();
                loc.getLongitude();
                intent.putExtra("Latitude", String.valueOf(loc.getLatitude())); //Double
                intent.putExtra("Longitude", String.valueOf(loc.getLongitude())); //Double
                intent.putExtra("Provider", loc.getProvider()); //String
                intent.putExtra("Altitude", loc.getAltitude());//Double
                intent.putExtra("Accuracy", loc.getAccuracy()); //float
                intent.putExtra("Speed", loc.getSpeed()); //float
                intent.putExtra("Bearing", loc.getBearing()); //float
                Log.v("LOC", String.valueOf(loc.getLatitude()));
                Log.v("LOC", String.valueOf(loc.getLongitude()));
                Log.v("LOC", loc.getProvider());
                Log.v("LOC", String.valueOf(loc.getAltitude()));
                Log.v("LOC", String.valueOf(loc.getAccuracy()));
                Log.v("LOC", String.valueOf(loc.getSpeed()));
                Log.v("LOC", String.valueOf(loc.getBearing()));

                sendBroadcast(intent);

            }
        }

        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }


        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }


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

        }

    }
}

MainActivity中调用Alarmreceiver:

Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);

manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);

最佳答案

MainActivity 类中创建一个 BroadcastReceiver 对象,如下所示:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Extract data included in the Intent

    }
};

也不要在 MainActivity 中使用定期检查,而是创建一个 Timer 对象并使用 sendBroadcast(intent) 发送定时广播。

关于java - Android Intent.getStringExtra() 在 Broadcastreceiver 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37995023/

相关文章:

java - 你如何在 Java 中从大写变成小写,我的代码输出有问题

java - 在 String 中扩展环境变量

android - setContentView 和 LayoutInflater 有什么区别?

java - 尝试在 Android 应用程序(java)上设置静音按钮

java - 从 onActivityResult 参数传递的 Intent 如何与我的应用程序配合使用?

Java.lang.VerifyError

java - Maven:组合 2 个配置文件时没有覆盖范围

android - 移动多个 fragment android

Android Google PlacePicker 显示重叠文本

Android - 可配置的目录?