我正在尝试在android中学习AlarmManager的功能。 我试图在每10秒后调用一次警报。但问题是我得到一个空白的屏幕。然后我发现我想在警报响起时打电话的意图没有被调用。请有人帮助我这个?
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");
}
}
答案 0 :(得分:1)
您正在调用PendingIntent错误:
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
了解你如何调用PendingIntent。 getBroadcast (this,0,intent,0)
这是错误的,因为您的AlarmReceiver是一个Activity(而不是像您正在告诉其未决意图的BroadcastReceiver)。试着这样称呼:
alarmIntent = PendingIntent.getActivity(this, 0, intent, 0);
您的问题只是错误使用待定意图:)
以下是文档:
http://developer.android.com/reference/android/app/PendingIntent.html
编辑:文档也说:
请注意,活动将在现有活动的上下文之外启动,因此您必须在Intent中使用Intent.FLAG_ACTIVITY_NEW_TASK启动标志。
因此,请确保您也这样做。