1
我想我的應用程序執行一些工作periodically.To做到這一點我使用AlarmManager
,但由於某種原因,它不會觸發任何事件。 清單XML:安卓:AlarmManager不會觸發報警事件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.user.alarm_test">
<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=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" android:enabled="true">
</receiver>
</application>
</manifest>
活動代碼:
public class MyActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel();
}
});
}
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 5000;
//schedule alarm to fire every 5 seconds
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis()+interval, interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancel() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
報警接收器:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
UPD:我發現manager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis()+interval, interval, pendingIntent);
(RTC代替ELAPSED_REALTIME_WAKEUP)的作品更好,但現在它只調用的onReceive一次。
您的清單中的接收器缺少操作字段 –
需要向接收器添加什麼操作?我在Google的文檔中看不到任何提示https://developer.android.com/training/scheduling/alarms.html – undefined