Android:无法在广播接收器中与MainActivity通信

时间:2016-11-06 16:46:47

标签: android broadcastreceiver android-context

我正在使用BroadcastReceiver。我的代码如下:

Settings2 class

public void set_notification_task()
    {
        Utilities.initParse(Settings2.this);
        get_notification_info();
    }

    public void get_notification_info()
    {
        ...
    }

    private void setAlarm_manager(Calendar c)
    {
        Intent intent = new Intent(Settings2.this, AlarmBroadcastReceiver.class);   
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Settings2.this, ALARM_RUEST, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    } 
}

`AlarmBroadcastReceiver

public class AlarmBroadcastReceiver extends BroadcastReceiver {
    final public static String ONE_TIME = "onetime";
    SharedPreferences settings;
    Settings2 setting_activity;

    public AlarmBroadcastReceiver() { }

    public AlarmBroadcastReceiver(Settings2 setting_Context){
        setting_activity =setting_Context;
    }

     @Override
     public void onReceive(Context context, Intent intent) 
     {
         PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
         //Acquire the lock
         wl.acquire();

         //You can do the processing here.
         Bundle extras = intent.getExtras();
         StringBuilder msgStr = new StringBuilder();

         if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
          //Make sure this intent has been sent by the one-time timer button.
          msgStr.append("One time Timer : ");
         }
         Format formatter = new SimpleDateFormat("hh:mm:ss a");
         msgStr.append(formatter.format(new Date()));

         Toast.makeText(context, "hello", Toast.LENGTH_LONG).show();
         wl.release();  //Release the lock

         setting_activity.set_notification_task(); //line 49
     }
}

logcat的:

11-07 00:28:02.514: E/AndroidRuntime(25045): FATAL EXCEPTION: main
11-07 00:28:02.514: E/AndroidRuntime(25045): Process: com.abc.wmn, PID: 25045
11-07 00:28:02.514: E/AndroidRuntime(25045): java.lang.RuntimeException: Unable to start receiver com.abc.utilities.AlarmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.abc.wmn.Settings2.set_notification_task()' on a null object reference
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2739)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.app.ActivityThread.access$1800(ActivityThread.java:153)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.os.Looper.loop(Looper.java:148)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.app.ActivityThread.main(ActivityThread.java:5438)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at java.lang.reflect.Method.invoke(Native Method)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
11-07 00:28:02.514: E/AndroidRuntime(25045): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.abc.wmn.Settings2.set_notification_task()' on a null object reference
11-07 00:28:02.514: E/AndroidRuntime(25045):    at com.abc.utilities.AlarmBroadcastReceiver.onReceive(AlarmBroadcastReceiver.java:49)
11-07 00:28:02.514: E/AndroidRuntime(25045):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
11-07 00:28:02.514: E/AndroidRuntime(25045):    ... 8 more

问题:

它遇到了上面的logcat问题:java.lang.RuntimeException: Unable to start receiver com.abc.utilities.AlarmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.abc.wmn.Settings2.set_notification_task()' on a null object reference,如何解决这个问题?

谢谢!

3 个答案:

答案 0 :(得分:1)

此处的问题是setting_activitynull,此处为:

setting_activity.set_notification_task();

这是因为永远不会调用设置AlarmBroadcastReceiver的{​​{1}}构造函数。由于setting_activity用于调用您的广播,因此它将是PendingIntent的默认构造函数,而不是您的自定义构造函数,在发送广播时会调用它。因此,AlarmBroadcastReceiver变量永远不会被初始化,因此setting_activity

答案 1 :(得分:0)

我已解决如下:

public class AlarmBroadcastReceiver extends BroadcastReceiver {
    final public static String ONE_TIME = "onetime";
    SharedPreferences settings;
    Settings2 setting_activity;

    public AlarmBroadcastReceiver() { }

    public AlarmBroadcastReceiver(Settings2 setting_Context){
        setting_activity =setting_Context;
    }

     @Override
     public void onReceive(Context context, Intent intent) 
     {
         PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
         //Acquire the lock
         wl.acquire();

         //You can do the processing here.
         Bundle extras = intent.getExtras();
         StringBuilder msgStr = new StringBuilder();

         if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
          //Make sure this intent has been sent by the one-time timer button.
          msgStr.append("One time Timer : ");
         }
         Format formatter = new SimpleDateFormat("hh:mm:ss a");
         msgStr.append(formatter.format(new Date()));

         Toast.makeText(context, "hello", Toast.LENGTH_LONG).show();
         wl.release();  //Release the lock

         setting_activity = new Settings2();
         setting_activity.set_notification_task();
     }
}

答案 2 :(得分:0)

正如Pathfinderelite所说,您无法从接收方访问您的活动。您可以做的是通过依赖注入使您的活动在Receiver中可用,或者更容易地通过在Activity中为自身实例创建静态链接。然后,Receiver可以获取实例,但它确实需要检查null,因为当调用onReceive时,不能保证Activity可用而且不为null。 (我为没有格式化而道歉,键盘背面报价已被破坏)。