2
不工作,這是我activiy_main.xmlAlarmManager的setRepeating()不重複,setInexactRepeating()在所有
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/textView1"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Example"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_marginTop="25dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Schedule"
android:onClick="scheduleAlarm"/>
</LinearLayout>
我MainActivity.java
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleAlarm(View V)
{
Long time = new GregorianCalendar().getTimeInMillis()+10*1000;
Intent intentAlarm = new Intent(this, AlarmReciever.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(1, time, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for 10 Seconds", Toast.LENGTH_LONG).show();
}
}
AlarmReceiver:
public class AlarmReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm Triggered", Toast.LENGTH_LONG).show();
}
}
我也將這些添加到我的清單文件中:
<receiver android:name=".AlarmReciever"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
這是我的整個示例應用程序。當我點擊Button
時,它會在10秒後執行我想要的操作,顯示Toast
說「觸發報警」。但用setRepeating()
方法只能使用一次。我想要的是它永遠重複,我會用這個代碼進行輪詢,但我不明白爲什麼它不會重複。我是否也應該使用setInexactRepeating()
進行投票?那一個根本不工作。
在此先感謝。