简体   繁体   中英

How can I display a text perday in my android app

I'm building a quotes app and i want the app to display a text on the startup page of my app, but i cant seems to get it right. Here is the code i tried...

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

Thanks in advance!

I don't think you need to update the quote from another thread because the user wont be looking at the startup page of your app for 24 hours. Just get a qoute according to the current date every time the start up page is created.

//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. If you want it to run every 24 hours, the math to convert it to milliseconds is 60000 * 60 * 24 . 60000 * 24 will give you 24 minutes.
  2. You should be using AlarmManager for such long intervals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM