如何在我的Android应用程序中每天显示文本

时间:2016-04-07 14:05:49

标签: java android

我正在构建一个引号应用程序,我希望该应用程序在我的应用程序的启动页面上显示文本,但我似乎无法正确。这是我试过的代码......

public class MainActivityFragment extends Fragment {
    public MainActivityFragment() {
    }
    final Handler h = new Handler();
    TextView lv, nam, cate;
    String randomQuotes, qNames, category;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        lv = (TextView)rootView.findViewById(R.id.quotes);
        nam = (TextView)rootView.findViewById(R.id.name);
        btn = (Button)rootView.findViewById(R.id.share);
        //List of quotes
        ListView allQuote = (ListView)rootView.findViewById(R.id.liv);

        //Display a text on screen in every 24hours
        final Random rand = new Random();
        h.post(new Runnable(){
            @Override
            public void run(){
                int x = rand.nextInt(AllQuotes.LIFE.length);
                lv.setText(AllQuotes.LIFE[x]);
                nam.setText(AllQuotes.NAMELIFE[x]);
                h.postDelayed(this, 60000 * 24);
            }
        });


        return rootView;
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

我认为您不需要更新其他线程的引用,因为用户不会在24小时内查看应用的启动页面。每次创建启动页面时,只需根据当前日期获得一个qoute。

//Display a text on screen in every 24 hours
//seed the random with the current date to get new random number only if the date is changed.
Calendar cal = Calendar.getInstance();
int seedVal = cal.get(Calendar.YEAR)*12*30+cal.get(Calendar.MONTH)*30+cal.get(Calendar.DAY_OF_MONTH);
Random rand = new Random(seedVal);
rand.nextInt(AllQuotes.LIFE.length);
lv.setText(AllQuotes.LIFE[x]);
nam.setText(AllQuotes.NAMELIFE[x]);

答案 1 :(得分:0)

  1. 如果您希望它每24小时运行一次,则将其转换为毫秒的数学运算为60000 * 60 * 2460000 * 24会给你24分钟。
  2. 您应该使用AlarmManager这么长的时间间隔。