编辑在我的清单中添加这一行解决了我的问题(Service
创建得很好)。
<service android:name=".TimersService" >
邮政
我目前正在尝试实现警报以通知用户倒计时已完成。我有一种方法createAlarm()
可以通过AlarmManager
. 此方法当前在 Fragment 内部调用。它看起来像这样:
private final void createAlarm(String name, long milliInFuture) {
Intent myIntent = new Intent(getActivity().getApplication(),
TimersService.class);
AlarmManager alarmManager = (AlarmManager) getActivity()
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(getActivity()
.getApplication(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP,
milliInFuture, pendingIntent);
}
我希望这种方法能够添加警报。即使设备处于睡眠模式,也应该调用警报。应该在某个时间milliInFuture
(即System.currentTimeMillis()
+ 某个时间)调用它。当警报响起时,它应该启动一个服务。服务如下。这Service
应该只做一件事:通知用户警报已经结束。我的Service
班级如下:
public class TimersService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = 3456;
public class LocalBinder extends Binder {
TimersService getService() {
return TimersService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
mNM.cancel(NOTIFICATION);
Toast.makeText(this, "Alarm", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
final NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
builder.setSmallIcon(R.drawable.clock_alarm);
builder.setContentTitle("Time is up");
builder.setContentText("SLIMS");
builder.setVibrate(new long[] { 0, 200, 100, 200 });
final Notification notification = builder.build();
mNM.notify(NOTIFICATION, notification);
NOTIFICATION += 1;
}
}
当我运行我的代码时,我的方法 createAlarm 被调用。但是我的服务永远不会被创建。我根据 Alexander's Fragotsis's one found here编写了这段代码。我的Service
课程灵感来自Service 类的 Android 参考资料。
知道为什么我Service
没有被调用吗?Manifest
关于警报、服务或通知,我应该写些什么吗?
感谢您的帮助
何和我将不胜感激有关我的代码的任何建议。如果您知道在固定时间后通知用户的更简单方法,请告诉我!