我正在创建一个 Android 应用,它使用 AlarmManager 通过播放声音来创建闹钟。为此,我首先创建一个 PendingIntent,为此我必须创建一个名为 AlarmReceiver 的类,它扩展了 BroadcastReceiver。在这个新类中,我重写了 onReceive 方法,我也在该方法中启动了声音。我现在拥有的东西有效。但是,作为更大项目的一部分,我稍后将从数据库中获取一些数据。关于我的问题,这个数据并不重要;重要的是,在分析完所有数据后,所有数据都会归结为一个 boolean 变量,即真或假。这个变量将在 MainActivity 中,我想在我的 BroadcastReceiver 类中访问它以检查它,如果为真,我将停止音乐。我已经检查了很多与这些相关的 SO 问题,但我仍然没有找到解决方案。
MainActivity 的代码是:
package com.example.alarmsound;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Calendar t = Calendar.getInstance();
t.add(Calendar.SECOND, 5);
Context context = this;
AlarmManager alarmMgr;
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.set(AlarmManager.RTC_WAKEUP, t.getTimeInMillis(), pendingIntent);
boolean result; //the variable I want to access to BroadcastReceiver class
}
}
BroadcastReceiver 类的代码是:
public class AlarmReceiver extends BroadcastReceiver{
public AlarmReceiver() {}
@Override
public void onReceive(Context context, Intent intent) {
final MediaPlayer mp = MediaPlayer.create(context, R.raw.music);
Log.d("Music", "It went here.");
mp.start();
//here, I want to access result
}
}
如果有任何帮助,我将不胜感激。
最佳答案
在主 Activity 中:
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("some_constant", result);
在您的广播接收器中:
boolean result = intent.getBooleanExtra("some_constant", false);
关于java - 如何在 BroadcastReceiver 中访问 MainActivity 的对象或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980117/