我已经阅读过这个问题的大多数帖子,但仍然无法让我的实施工作,你能帮忙吗?
基本上我想从一个Activity中启动一个BroadcastReceiver,每隔10秒做一次事。所以我设置了警报,但代码实际上从未到达“onReceive()”...我无法发现我的代码与其他示例有任何区别,你能看一下吗?
还要提一下,我没有在清单文件中放置接收器,因为我知道不需要它,因为我在活动中注册它。
谢谢!
package alarm.in;
import alarm.in.activity.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class activityActivity extends Activity {
private Alarm alarm;
private static final String TAG = "AlarmInActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarm = new Alarm();
}
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(ALARM_SERVICE);
registerReceiver(alarm, filter);
}
public void onPause() {
super.onPause();
this.unregisterReceiver(alarm);
}
public void setAlarm(View view){
alarm.SetAlarm(getBaseContext(),1,10);
}
public void cancelAlarm(View view){
alarm.CancelAlarm(getBaseContext());
}
private class Alarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
Log.d(TAG, "Alarm Worked!");
wl.release();
}
public void SetAlarm(Context context, int minutes, int seconds)
{
AlarmManager am=(AlarmManager)context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * seconds * minutes, pi); // Millisec * Second * Minute
Log.d(TAG, "AlarmSet");
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
Log.d(TAG, "AlarmCancel");
}
}
}
答案 0 :(得分:3)
您注册了接收者,但忘记将动作发送给接收者:
Intent intent = new Intent(ALARM_SERVICE);
sendBroadcast(intent);