-1

我不断收到以下错误:广播接收机空指针的Android

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

当我尝试从我的服务类接收广播。

服务:

@Override 
public void onDestroy(){ 
    super.onDestroy(); 
    Intent intent = new Intent("UpdateLocation"); 
    intent.putExtra("Location",journ); 
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
} 

这是代码发送广播发送自定义对象(Journ)到我的主要活动。

主营:

@Override 
protected void onCreate(Bundle savedInstanceState) 

    LocalBroadcastManager.getInstance(this).registerReceiver(
      mReceiver, new IntentFilter("UpdateLocation")); 

    //Listen for service to send location data 
    mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      temp= intent.getExtras().getParcelable("Location"); 
     } 
    }; 
} 

    @Override 
    public void onPause() { 
     if (!tracking) { 
      finish(); 
     } 
     //Run service in background to keep track of location 
    startService(new Intent(this, locationService.class)); 
     super.onPause(); 
    } 

    @Override 
    public void onResume() { 
     if (!tracking) { 
      return; 
     } 
     if (mGoogleApiClient != null) { 
      //Reconnect to google maps 
      mGoogleApiClient.reconnect(); 
     } 
     stopService(new Intent(this, locationService.class)); 
     super.onResume(); 
    } 

我不知道如何去这样做,我想从它运行我的服务类传递对象时,我的应用程序在后台运行,当它恢复服务应该停止并将收集的数据发送给我的主要活动。

但是,这不起作用,有什么想法?

如果人们想知道我的创建方法确实包含更多的代码,但我认为没有必要包含它。

回答

1

在onCreate mReciever是一个空对象(如果您以前没有指定它),所以您应该在注册接收器之前分配它。 更换此零件:

mReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     temp= intent.getExtras().getParcelable("Location"); 
    } 
}; 

//Listen for service to send location data 
LocalBroadcastManager.getInstance(this) 
    .registerReceiver(mReceiver, new IntentFilter("UpdateLocation"));