[英]running a background service for an alarm on android?
Within my application a user can set a certain time, i wish for a notification to be displayed on the screen when the time reaches the set time (basically an alarm) out wheather the application is currently running or not. 在我的应用程序中,用户可以设置一个特定的时间,我希望当该时间达到设置的时间(基本上是警报)时,无论应用程序当前是否正在运行,通知都会显示在屏幕上。
How would i go about doing this? 我将如何去做?
No use getting into a long answer, you obviously didn't search much... 冗长的答案毫无用处,您显然搜索得并不多。
http://developer.android.com/reference/android/app/AlarmManager.html http://developer.android.com/reference/android/app/AlarmManager.html
Check now, I have updated the code. 现在检查,我已经更新了代码。
Here is the code for CountDownTimer. 这是CountDownTimer的代码。 and when time completes it sends an notification. 当时间结束时,它会发送通知。 You can use it in Service or in a normal Activity. 您可以在“服务”或常规活动中使用它。
public String ns = Context.NOTIFICATION_SERVICE;
public NotificationManager mNotificationManager;
Notification notification;
PendingIntent contentIntent;
Intent notificationIntent;
public class Main extends Activity{
private final long startTime = 50000;
private final long interval = 1000;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int time=Integer.parseInt(editText.getText().toString());
time=time*1000;
startTime = time;
// place this code on button listener if you want.
countDownTimer = new MyTimer(startTime, interval);
}
}
public class MyTimer extends CountDownTimer
{
public MyTimer(long startTime, long interval)
{
super(startTime, interval);
}
@Override
public void onFinish()
{
mNotificationManager = (NotificationManager) getSystemService(ns);
notificationIntent = new Intent(this, MyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification = new Notification(R.drawable.icon,"Time up..", System.currentTimeMillis());
notification.setLatestEventInfo(this, "CallingaCab", "YOUR TIME COMPLETED", contentIntent);
mNotificationManager.notify(0, notification);
startActivity(notificationIntent);
}
@Override
public void onTick(long millisUntilFinished)
{
//Perform what do you want on each tick.
}
}
}
Please create service to extends Service class that service run on background and check what ever you want to. 请创建服务以扩展该服务类在后台运行的服务类,并检查您想要执行的操作。 here you can find service example . 在这里您可以找到服务示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.