【问题标题】:android stopwatch/timer app - switching back to app when time runs outandroid秒表/计时器应用程序 - 时间用完时切换回应用程序
【发布时间】:2014-05-22 13:24:28
【问题描述】:

我正在开发一个应用程序,如标题中所述。即使用户启动/切换到另一个应用程序,我也需要以某种方式管理该应用程序将运行/计算时间。好吧,正如我从 stackoverflow.com 上的另一个讨论中了解到的那样,没有必要创建在后台运行的服务,也无需在应用程序不活动时计算时间给处理器带来毫无意义的负担。

需要做的就是存储用户切换到另一个应用程序的当前时间,将其与他切换回来的时间进行比较,并根据这些时间之间的差异更新 UI。那是秒表模式。在定时器模式下,我需要根据时间自动切换回应用程序,即在后台运行时显示应用程序的 UI。什么是适合这个的最佳解决方案,你能给我一些简单的例子吗?

【问题讨论】:

  • 服务有什么问题???服务是更好的方法。
  • 服务用于后台长时间运行的进程,不是吗?我只需要在时间用完后切换回应用程序并显示一些警报窗口或播放声音。

标签: java android service timer stopwatch


【解决方案1】:

为此使用AlarmManagerAlarmManager 允许您安排任务并在它们被触发时得到通知。

【讨论】:

    【解决方案2】:

    所以使用 AlarmManager

    public class MainActivity extends Activity
    {
       @Override
       public void onCreate(Bundle savedInstanceState) 
      {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                //call function where you want
                timeout();
      }
    
    public void timeout()
    {       //time in milliseconds 1 minute
            Long time = new GregorianCalendar().getTimeInMillis()+60*1000; //i.e.60*1000=1minute
            // create an Intent and set the class which will execute when Alarm triggers, here we have
            Intent intentAlarm = new Intent(this, AlarmReciever.class);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    
        }
    }
    

    这是广播类:

     public class AlarmReciever extends BroadcastReceiver
     {
         @Override
            public void onReceive(Context context, Intent intent)
            {
                    // show dialog or what you want
    
             }
    
    }
    

    别忘了编辑 AndroidMainfest:

     //permission
     <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
     //our receiver
     <receiver android:name=".AlarmReciever"/> 
    

    【讨论】:

    • 在 AlarmReciever 类中,我应该通过 startactivity() 方法编写切换回应用程序的代码?
    • 是的,您可以直接切换活动或显示对话框或播放一些声音或您想要的...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多