我正在尝试将一个整数值从一个Activity发送到一个Broadcast接收器,这是我的Activity中的方法代码:
public void vibrator(View view){
if (((ToggleButton) view).isChecked()) {
Toast.makeText(getApplicationContext(), "Vibration ON",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(AddAlarm.this, AlarmReceiver.class);
intent.putExtra("vibrator",1);
}
}
现在,从广播接收器,当我尝试调用时:
Intent receive = getIntent();
这是一个错误,但如何以正确的方式执行此操作?
AlarmReceiver中的代码:
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
int vibrator = intent.getIntExtra("vibrator", 1);
PendingIntent sender = PendingIntent.getBroadcast(context, 0,
intent, 0);
Uri alarmUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//intent to call the activity which shows on ringing
Intent myIntent = new Intent(context, Time_Date.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
//display that alarm is ringing
Toast.makeText(context, "Alarm Ringing...!!!",
Toast.LENGTH_LONG).show();
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
if(vibrator==1)
{
Log.w("the value I get is","given as"+vibrator);
}
}
}
答案 0 :(得分:2)
从广播接收器调用getIntent()时出错
getIntent()
方法不是来自BroadcastReceiver
类。
在BroadcastReceiver
中获取使用sendBroadcast
方法发送的意图使用onReceive
方法第二个参数Intent
:
@Override
public void onReceive(Context context, Intent intent) {
int vibrator=intent.getIntExtra("vibrator",1);
}