我有两个问题的警报管理器。一个是我想每10秒重复一次报警,其他是我的广播接收器在10秒后调用。
当我使用Activity而不是广播接收器时,它正在工作但广播接收器不工作。并且时间不合适有时它在1分钟内工作,有时它工作50秒。但我需要每10秒钟。
我的代码是:
buttonStart.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
long tenMin = 1000/5 ;//here is 30 seconds
Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,
0, intent, 0);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tenMin, pendingIntent);
}});
BoradcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
}
}
Manifest file:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyAlarmService" />
<receiver
android:name=".MyBroadcastReceiver"
android:process=":remote"></receiver>
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
答案 0 :(得分:2)
使用:
<强>活动强>:
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0, intent, 0);
10秒重复间隔,
repeatingInterval = 10 *1000; //interval in milli seconds for 10sec
AlarmManager alarmManager =(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
alarmManager .setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), repeatingInterval , pendingIntent);
它应该有用。