在android上运行警报的后台服务?

时间:2011-08-31 13:22:59

标签: java android service alarm

在我的应用程序中,用户可以设置一定的时间,我希望当时间到达应用程序当前正在运行的设置时间(基本上是警报)时,屏幕上会显示通知。

我将如何做到这一点?

3 个答案:

答案 0 :(得分:2)

没有用到很长的答案,你显然没有多搜索......

http://developer.android.com/reference/android/app/AlarmManager.html

答案 1 :(得分:2)

立即检查,我已更新代码。

这是CountDownTimer的代码。 当时间完成时,它会发送通知。 您可以在服务中或在正常活动中使用它。

     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.
                }
            }
        }

答案 2 :(得分:0)

请创建服务以扩展服务在后台运行的服务类,并检查您想要的内容。 here you can find service example