我是Android新手。我正在尝试创建一个使用BroadcastReceiver
来执行由重复警报触发的主要活动的函数的应用程序。我读到我必须动态注册我所做的broadcastReceiver
- 这是为了能够在主要活动上执行该功能。我面临的问题是,一旦退出应用程序,alarm
就会停止工作。我读到这是设计 - 有没有办法克服这个问题,还是我必须使用service
?提前谢谢。
示例代码:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "from AlarmReceiver", Toast.LENGTH_SHORT).show();
}
}
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private AlarmManager manager;
private AlarmReceiver myReceiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new AlarmReceiver();
IntentFilter myIntentFilter = new IntentFilter("ANY_ACTION");
registerReceiver(myReceiver, myIntentFilter);
Intent myIntent = new Intent();
myIntent.setAction("ANY_ACTION");
pendingIntent = PendingIntent.getBroadcast(this, 0,myIntent,0);
}
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 1500;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
我认为,当您的应用未运行时,闹钟停止工作的原因是您在registerReceiver
本地注册 AlarmReceiver 。如果您想注册AlarmReceiver以便即使您的应用程序未运行也能继续工作,您需要在AndroidManifest.xml
内注册它。
首先,将您的收件人添加到AndroidManifest.xml
,如下所示:
<application>
//...
<receiver android:name=".AlarmReceiver">
</receiver>
//...
</application>
并设置你的闹钟(记住:不要设置闹钟间隔太短,设置至少1分钟;你在你的代码中设置你的间隔1.5秒 - 它可能不起作用):
int interval = 60 * 1000;
Intent intent=new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
在onRecieve中触发警报时,只需执行您想要执行的操作:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
SharedPreferences sharedPreferences = context.getSharedPreferences("Settings", 0);
int iDefValue=0;
int iDayAlarmVal= sharedPreferences.getInt("something", iDefValue);
// and so on...
}
}