Intent.getAction()抛出Null + Android

时间:2011-03-06 20:26:07

标签: android

我已经编写了BroadcastReceiver用于报警应用程序。在onReceive方法中,我正在阅读Intent.getAction()。 它在所有版本* 中运行良好,但SDK版本1.5除外,它会抛出空指针异常 * 。我在另一个我正在调用broadcastReceiver的活动中设置操作。这个你能帮我吗。下面是接收器和活动类的代码片段,

ProfileActivity.java


public static final String STARTALARMACTION = "android.intent.driodaceapps.action.STARTPROFILE";

public static final String STOPALARMACTION = "android.intent.driodaceapps.action.STOPPROFILE";

AlarmManager alarmMan = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent startIntent = new Intent(this,AlarmReceiver.class);

startIntent.setAction(STARTALARMACTION);

Intent stopIntent = new Intent(this,AlarmReceiver.class);

stopIntent.setAction(STOPALARMACTION+intentposition);

AlarmReceiver.java

@Override
public void onReceive(Context context,Intent intent){

    String intentAction = intent.getAction(); 

    Log.d(TAG,"Intent:"+intentAction); **//throwing null**

在收到错误后,我通过给出.manifest文件中的操作来试试运气。但没用。

请帮帮我。

感谢。

2 个答案:

答案 0 :(得分:6)

来自BroadcastReceiver.onReceive()...

的文档
  

registerReceiver(BroadcastReceiver,IntentFilter)和应用程序清单中使用的Intent过滤器不保证是独占的

     

出于这个原因,onReceive()实现应该只响应已知的操作,忽略他们可能收到的任何意外的Intents

我并不完全理解上述任何一个陈述的含义,但似乎两者中的第二个是应该编写onReceive()处理程序来应对意外情况。

请记住,Intent不需要具有关联的“动作”(它们可以简单地用于在不同实体之间传递数据)。如果Intent没有设置任何操作,Intent.getAction()将返回null,并且尝试记录intentAction将调用NPE。

你确定意图是你自己的意图而不是另一个已经发现它是接收者的方式吗?我不熟悉v1.5,但可能的事情可能有不同的方式 - 不太可能,但可能。

我认为简单的尝试就是简单地测试一下intentAction以查看它是否为null并且如果它是忽略它(即退出onReceive()处理程序,假设意图不是你自己的意图)。值得一试。

答案 1 :(得分:2)

继@ Squonk的优秀回复之后,我将以下代码放入BroadcastReciever onReceive {/ p}中:

if (intent != null) {
    if(intent.getAction() != null){
        Log.i(TAG, "Intent: " + intent.getAction());
    }else{
        Log.i(TAG, "Intent: !null, Action: null");
    }
}else{
    Log.i(TAG, "Intent: null");
}

我的接收器每60秒启动一次,但其他东西正在调用它:

12-03 08:42:05.566 Intent: WEEKLY_CHECK
12-03 08:42:32.990 Intent: !null, Action: null
12-03 08:42:33.175 Intent: WEEKLY_CHECK
12-03 08:43:32.990 Intent: WEEKLY_CHECK
12-03 08:43:33.025 Intent: !null, Action: null
12-03 08:43:33.057 Intent: WEEKLY_CHECK
12-03 08:44:32.990 Intent: WEEKLY_CHECK
12-03 08:44:33.069 Intent: !null, Action: null
12-03 08:44:33.102 Intent: WEEKLY_CHECK

从而确认了文档中的内容。