我正在开发一个类似类型的应用程序。我使用广播接收器和使用警报管理器安排它的服务,这样你就没有太多开销,比如运行一个必须保持活动状态的计时器。
这是我的主要活动。我用按钮启动序列。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
Button.OnClickListener btnOnClickListener = new Button.OnClickListener() {
@Override
public void onClick(View v) {
if (v == btn_splash) {
initiateAlarm(true);
Toast.makeText(MainActivity.this, " alarm scheduled", Toast.LENGTH_LONG).show();
}
} else if (v == btn_cancel)
{
initiateAlarm(false);
Toast.makeText(MainActivity.this, " alarm stopped", Toast.LENGTH_LONG).show();
}
}
};
}
public void initiateAlarm(Boolean bactive) {
alarmUp = false;
alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(this, YourService.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
Toast.makeText(this, " before scheduling Alarm is already active", Toast.LENGTH_LONG).show();
} else {
YourReceiver.scheduleAlarms(this, prefDuration, bactive);
Toast.makeText(this, "alarms were just scheduled", Toast.LENGTH_LONG).show();
}
alarmUp = false;
alarmUp = (PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(this, YourService.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
Toast.makeText(this, " after scheduling Alarm is already active", Toast.LENGTH_LONG).show();
}
}
}
这是在警报管理器中安排服务的 YourReceiver。
public class YourReciever extends BroadcastReceiver {
private static final String TAG = "YourReciever";
@Override
public void onReceive(Context ctxt, Intent i) {
context = ctxt;
scheduleAlarms(ctxt, (long) 3600001, true); // 1 hour - not used
}
static void scheduleAlarms(Context ctxt, Long duration, Boolean bactive) {
Log.e(TAG, " ... scheduleAlarms ");
SharedPreferences preferences;
preferences = PreferenceManager.getDefaultSharedPreferences(ctxt);
prefDuration = preferences.getLong(PREF_DURATION, 3600000); // 1 hour
Log.e(TAG, " ... onReceive ... duration: " + duration);
AlarmManager mgr=
(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(ctxt, YourService.class);
PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + duration, duration, pi);
if (bactive == false) {
mgr.cancel(pi);
}
}
}
最后是服务类
public class YourService extends IntentService {
public YourService() {
super("YourService");
Log.e(TAG, " ... YourService");
}
@Override
protected void onHandleIntent(Intent intent) {
//
// The action you want to perform.
//
}
}
像这样的东西需要在清单中。
<service
android:name="com.yourpackagename.YourService"
android:exported="true"/>
希望这可以帮助。
祝你有美好的一天。