Android BroadcastReceiver in Service在向其发送广播时给出空指针异常

时间:2016-07-05 21:00:06

标签: java android service broadcast android-broadcast

我的服务中有广播接收器,当我从我的活动向其发送广播以停止服务时,我收到以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)' on a null object reference

这是我的服务类

public class PhraseService extends Service{

public static List<Phrase> phrases;
private Context context;

private static final String PHRASE_SERVICE_BROADCAST_ID = "com.cryogenos.safephrase.PHRASE_SERVICE_BROADCAST_ID";
private BroadcastReceiver command_broadcast_receiver;


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.context = getApplicationContext();
    LocalBroadcastManager.getInstance(this).registerReceiver(command_broadcast_receiver, new IntentFilter(PHRASE_SERVICE_BROADCAST_ID));

    Log.i("COS", "STARTED SELF");

    /* Handle any command sent by the app here */
    command_broadcast_receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("COS", "CALLED?");
            try {
                String command = intent.getStringExtra("command");

                /* Based on the command given, perform an action */
                switch (command) {
                    case "RESTART RECOGNIZER":
                        break;
                    case "STOP":
                        Toast.makeText(context, "Phrase Listener Stopped", Toast.LENGTH_SHORT).show();
                        stopSelf();
                        break;
                }
            }
            catch (Exception e){}
        }
    };
    Intent notif_intent = new Intent(this, Home.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, notif_intent, 0);
    Notification notif = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Phrase Listener")
            .setContentText("Listening for Phrases")
            .setContentIntent(pi)
            .build();

    startForeground(34994, notif);
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(command_broadcast_receiver);
    super.onDestroy();
}


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

以下是我发送广播的活动

public class SettingsModel {

private Context context;
private static final String PHRASE_SERVICE_BROADCAST_ID = "com.cryogenos.safephrase.PHRASE_SERVICE_BROADCAST_ID";
private LocalBroadcastManager local_broadcast_manager;

public SettingsModel(Context context) {
    this.context = context;
    local_broadcast_manager = LocalBroadcastManager.getInstance(context);
}

public void handleSwitch(SettingsSwitch settings_switch, boolean status){
    switch (settings_switch){
        case POWER:
            if(status) {
                Intent i = new Intent(context, PhraseService.class);
                context.startService(i);
            }
            else{
                Intent i = new Intent(PHRASE_SERVICE_BROADCAST_ID);
                i.putExtra("command", "STOP");
                local_broadcast_manager.sendBroadcast(i);
            }
            break;
        case VIBRATE:
            break;
        case RING:
            break;
        case TIMER:
            break;
    }
}
}

我的服务是连续运行,只有当我告诉它时,它应该停止。这就是我将其设置为前台服务的原因。这里的问题是,当我尝试向它广播时,我一直收到错误。

1 个答案:

答案 0 :(得分:11)

您在初始化之前注册了brodcastreceiver。因此,请尝试在初始化后移动注册,如下所示:

/* Handle any command sent by the app here */
    command_broadcast_receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("COS", "CALLED?");
            try {
                String command = intent.getStringExtra("command");

                /* Based on the command given, perform an action */
                switch (command) {
                    case "RESTART RECOGNIZER":
                        break;
                    case "STOP":
                        Toast.makeText(context, "Phrase Listener Stopped", Toast.LENGTH_SHORT).show();
                        stopSelf();
                        break;
                }
            }
            catch (Exception e){}
        }
    };
LocalBroadcastManager.getInstance(this).registerReceiver(command_broadcast_receiver, new IntentFilter(PHRASE_SERVICE_BROADCAST_ID));

此外,您的SettingsModel不是活动,因为它不会延伸Activity