从活动中将字符串传递给Java类

时间:2016-02-29 19:06:19

标签: android android-intent broadcastreceiver

我需要将一个字符串值从我的main活动传递给一个实现BroadcastReceiver的Java类。基本上我想从AddNewPrescriptionsActivity.java中的EditText获取String值并将其传递给AlarmReceiver.java。似乎我不能使用Intent或Bundle传递它,所以还有另一种方法吗?我在下面有一些代码..

以下是我的一些名为AddNewPrescriptionsActivity.java的MainActivity:

        public void onClick(View v) {

        if (v == btnSave) {
        calSet.getTime();
        if (calSet.compareTo(calNow) <= 0) {
        //Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
        }
        setAlarm(calSet);
        Toast.makeText(AddNewPrescriptionsActivity.this, "Notification Created", Toast.LENGTH_LONG).show();

                        }
                    }


    private void setAlarm(Calendar targetCal) {

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

}

这是我的AlarmReceiver.class,它实现了BroadcastReceiver

   public class AlarmReceiver extends BroadcastReceiver {

    @Override
public void onReceive(Context arg0, Intent arg1) {

        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(arg0, notification);
        r.play();

        Toast.makeText(arg0, "Received" , Toast.LENGTH_LONG).show();


}}

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你需要从你的活动中向你的广播接收者发送一个字符串值。为此,请在您的活动中:

    @Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();

  Log.i("Receiver", "Broadcast received: " + action);

  if(action.equals("my.action.string")){
     String state = intent.getExtras().getString("state");
     //do your stuff
  }
}

在BroadcastReceiver中:

<receiver android:name=".YourBroadcastReceiver" android:enabled="true">
<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    <action android:name="my.action.string" />
    <!-- and some more actions if you want -->
</intent-filter>

在manifest.xml中:

java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

希望它有所帮助!