在将数据从Service传递到Broadcast Receiver时获取NullpointerException

时间:2017-03-25 10:58:22

标签: android android-intent nullpointerexception broadcastreceiver android-service

我有一个服务,我从MainActivity开始。然后在onStartCommand()中我注册到Broadcast Receivers。但是我将String值传递给Service by Bundle的广播接收器。但是我在广播接收器的onReceiver()中得到NullpointerException。这是我的活动代码。

@Override
protected void onStart() {
    super.onStart();
    if (bluetoothService == null) {
        kolamDeviceDialog();
    } else {
        Log.e("MenuBluetoothService", bluetoothService.getStatus() + "");
        if (!bluetoothService.getStatus()) {
            kolamDeviceDialog();
        }
    }
}

private void kolamDeviceDialog() {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(MenuActivity.this)
            .title("Select Bot")
            .items(scanTypes)
            .itemsCallback(new MaterialDialog.ListCallback() {
                @Override
                public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                    if (position == 0) {
                        isSmallBot = false;
                        KolamDevice kolamDevice = new KolamDevice();
                        Intent intent = new Intent(MenuActivity.this, BluetoothService.class);
                        intent.putExtra("Address", kolamDevice.getBigBotAddress());
                        intent.putExtra("Name", kolamDevice.getBigBotName());
                        startService(intent);
                        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
                    } else {
                        isSmallBot = true;
                        KolamDevice kolamDevice = new KolamDevice();
                        Intent intent = new Intent(MenuActivity.this, BluetoothService.class);
                        intent.putExtra("Address", kolamDevice.getSmallBotAddress());
                        intent.putExtra("Name", kolamDevice.getSmallBotName());
                        startService(intent);
                        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
                    }
                }
            });
    builder.show();
}

@Override
protected void onStop() {
    super.onStop();
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

这是我的服务代码。

public class BluetoothService extends Service {

private final IBinder mBinder = new MyBinder();
private SmoothBluetooth smoothBluetooth;
private static Device device;
String address, name;
private List<Integer> mBuffer = new ArrayList<>();
private List<String> mResponseBuffer = new ArrayList<>();

public BluetoothService() {
}

@Override
public void onCreate() {
    super.onCreate();
    Log.e("BluetoothService", "onCreated");
    // startForeground(1, new Notification());
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("BluetoothService", "Killed");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("BluetoothService", "Started");
    startForeground(1, new Notification());
    Bundle extras = intent.getExtras();
    if (extras != null) {
        address = extras.getString("Address");
        name = extras.getString("Name");
    }
    Log.e("Address", address);
    Log.e("name", name);
    smoothBluetooth = new SmoothBluetooth(this);
    smoothBluetooth.setListener(mListener);

    startScheduleReceiver();
    startBootReceiver();

    if (smoothBluetooth.isBluetoothEnabled()) {
        if (!smoothBluetooth.isConnected()) {
            device = new Device(name, address, true);
            smoothBluetooth.tryConnection();
        }
    } else {
        device = new Device(name, address, true);
        smoothBluetooth.tryConnection();

    }
    return Service.START_NOT_STICKY;
}

private void startBootReceiver() {
    Intent broadcastIntent = new Intent(this, MyStartServiceReceiver.class);
    Bundle bundle = new Bundle();
    broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    bundle.putString("BotType", name);
    broadcastIntent.putExtras(bundle);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager service = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    // start 1 second after boot completed
    cal.add(Calendar.SECOND, 1);
    // fetch every 1 second
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
}

private void startScheduleReceiver() {
    Intent broadcastIntent = new Intent(this, MyScheduleReceiver.class);
    Bundle bundle = new Bundle();
    broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    bundle.putString("BotType", name);
    broadcastIntent.putExtras(bundle);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager service = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    // start 1 second after boot completed
    cal.add(Calendar.SECOND, 1);
    // fetch every 1 second
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
}


@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

public class MyBinder extends Binder {
    BluetoothService getService() {
        return BluetoothService.this;
    }
}


public boolean getStatus() {
    Log.e("BluetoothServiceStatus", smoothBluetooth.isConnected() + "");
    return smoothBluetooth.isConnected();
}

这是我的第一个广播接收器代码。

public class MyStartServiceReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    Log.e("BootReceiver", "Started");
    Bundle bundle = intent.getExtras();
    String name = bundle.getString("BotType");
    if (name.equalsIgnoreCase("TEAMRED1")) {
        KolamDevice kolamDevice = new KolamDevice();
        Intent bigBotIntent = new Intent(context, BluetoothService.class);
        bigBotIntent.putExtra("Address", kolamDevice.getBigBotAddress());
        bigBotIntent.putExtra("Name", kolamDevice.getBigBotName());
        context.startService(bigBotIntent);
    } else {
        KolamDevice kolamDevice = new KolamDevice();
        Intent smallBotIntent = new Intent(context, BluetoothService.class);
        smallBotIntent.putExtra("Address", kolamDevice.getSmallBotAddress());
        smallBotIntent.putExtra("Name", kolamDevice.getSmallBotName());
        context.startService(smallBotIntent);
    }
}

}

这是我的第二个广播接收器代码。

public class MyScheduleReceiver extends BroadcastReceiver {

private String name, address;

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle bundle = intent.getExtras();
    String smallBot = bundle.getString("BotType");
    if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
            Log.e("BluetoothCondition", "On");
            Log.e("Bot", smallBot);


        } else if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
            Log.e("BluetoothCondition", "Off");
            Log.e("Bot", smallBot);
        }
    }
}

}

这也是logcat错误。

java.lang.RuntimeException: Unable to start receiver com.ignite.a01hw909350.kolamdemo.MyScheduleReceiver: java.lang.NullPointerException: println needs a message
                                                                                  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2645)
                                                                                  at android.app.ActivityThread.access$1800(ActivityThread.java:154)
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5290)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                  at android.util.Log.println_native(Native Method)
                                                                                  at android.util.Log.e(Log.java:232)
                                                                                  at com.ignite.a01hw909350.kolamdemo.MyScheduleReceiver.onReceive(MyScheduleReceiver.java:28)
                                                                                  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2638)
                                                                                  at android.app.ActivityThread.access$1800(ActivityThread.java:154) 
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399) 
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                  at android.os.Looper.loop(Looper.java:135) 
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5290) 
                                                                                  at java.lang.reflect.Method.invoke(Native Method) 
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)

请告诉我为什么我在两个广播接收器的onReceiver()中都为空。

1 个答案:

答案 0 :(得分:0)

您从服务到广播接收器的传递值是有问题的。

使用此:保持简单

对于接收者:

Intent broadcastIntent = new Intent(this, MyStartServiceReceiver.class);
broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
broadcastIntent.putExtra("BotType", name);
//sendBroadcast(broadcastIntent);

现在在onReceive()

 @Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();

  if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
     String smallBot = intent.getExtras().getString("BotType");
     //do your stuff
  }
}

另外添加:

if(smallBot!= null)
    Log.e("Bot", smallBot);