从BroadcastReceiver发送额外数据Context是Null

时间:2015-08-18 15:42:23

标签: android android-intent service broadcastreceiver

我只想弄清楚服务,BroadcastReceivers和所有这些东西是如何工作的。

我写了一个Receiver,当屏幕状态发生变化时触发。比它打开一个服务,它打开一个放在锁定屏幕上的活动。只要我的应用程序正在运行,该工作正常,但是当我的应用程序已经死亡时,传递给我的BroadcastReceiver的上下文为空。而且我无法将我的数据传输到服务,因为Intent也是空的。

我希望有人知道如何解决这个问题。

我的代码如下:

启动服务的活动:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent service = new Intent(this,UpdateService.class);
    startService(service);

    setContentView(R.layout.activity_main);
}

服务:

public class UpdateService extends Service {
@Override
public void onCreate() {
    super.onCreate();
    // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new ScreenReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public int onStartCommand(Intent intent,int flags , int startId) {
    boolean screenOn = intent.getBooleanExtra("screen_state", false);
    if (!screenOn) {
        // Screen is on
    } else {
        // Screen is off
        Intent myIntent = new Intent(this,MyActivity.class);
        // The Flag is important to open an Acitivy from the service.
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(myIntent);
    }
    return Service.START_STICKY;
}

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

}

BroadcastReceiver:

public class ScreenReceiver extends BroadcastReceiver {
private boolean screenOff;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    Intent intent2open;
    intent2open = new Intent(context, UpdateService.class);
    intent2open.putExtra("screen_state", screenOff);
    context.startService(intent2open);
}

}

1 个答案:

答案 0 :(得分:0)

我认为您最好直接在Manifest中注册Receiver并将this更改为getApplicationContext()或启动活动以启动Intent,但请确保它使用{ {1}}方法,因此用户甚至不知道另一个活动被调用!

修改

我想我明白你的问题是什么。我修改了您的代码并删除了该服务,因为我认为这不是必需的。

finish()

您的广播接收器。

  @Override
protected void onCreate(Bundle.savedInstanceState) {

public boolean ScreenState =     true; 
super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);
}

protected void onNewIntent(Intent    intent) { 
 ScreenState =     intent.getExtra("screen_state"))
if(ScreenState==false)
 { 
      //**Do whatever you want**
 }
 else
{
     //False alarm close the activity.
     finish();
}
}

如果有效,请告诉我。 请记住广播接收器将我的活动更改为您的活动名称。