gpt4 book ai didi

java - Android 中未调用闹钟

转载 作者:行者123 更新时间:2023-12-01 10:06:48 25 4
gpt4 key购买 nike

我正在尝试学习Android中AlarmManager的功能。我试图每 10 秒后调用一次警报。但问题是我得到一个空白屏幕。然后我发现我在警报唤醒时尝试调用的 Intent 没有被调用。请有人帮助我有了这个?

MainActivity.java

public class MainActivity extends AppCompatActivity {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Log.d("asd","initialized alarmintent");
alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime()+10*1000, alarmIntent);

Log.d("asd", "alarm set");
}
}

AlarmReceiver.java

public class AlarmReceiver extends AppCompatActivity
{
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent_layout);
Log.d("asd","writing textview");
tv=(TextView)findViewById(R.id.textview);
tv.setText("called");
}

}

最佳答案

您调用 PendingIntent 是错误的:

Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

看看你如何调用 PendingIntent。getBroadcast(this, 0, Intent, 0)

这是错误的,因为您的 AlarmReceiver 是一个 Activity (而不是像您所说的待处理 Intent 那样的 BroadcastReceiver )。尝试这样调用它:

alarmIntent = PendingIntent.getActivity(this, 0, intent, 0);

您的问题只是错误地使用了未决 Intent :)

这是文档:

http://developer.android.com/reference/android/app/PendingIntent.html

编辑:文档还说:

Note that the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.

所以请确保您也这样做。

关于java - Android 中未调用闹钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36388100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com