简体   繁体   中英

How can I disable my Button after one click and enable it after 24 hours or on a Next Date?

How can I disable my Button after one click and enable it after 24 hours or on a Next Date? I am new to Android.

This is my code:

public class ShareDetailActivitySW extends AppCompatActivity implements View.OnClickListener {

    private btn_share_sw;
  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_detail);

        btn_share_sw = findViewById(R.id.btn_share_sw);


        // Please do change in my code I will copy it 
        // This is the button to disable 

        btn_share_sw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
                    shareIntent.putExtra(Intent.EXTRA_TEXT, AppLink);
                    startActivityForResult(Intent.createChooser(shareIntent, "Share with"), INSTALLCODE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Inside onClick():

  1. Save the current timestamp using SharedPreferences API.
  2. Create an alarm using AlarmManager API ( set() or setExact() based on your use case).

Inside onCreate():

Check if the interval between the saved timestamp and current timestamp is greater then a day. If yes, enable the button; else disable it.

Also register a broadcast receiver to receive the set alarms ( example ). When the set alarm is received, enable the button.

If you want to survive a reboot, you might want to restart the set alarm ( link ).

The usage of AlarmManager is to make sure the button state updates even if the user is in the ShareDetailActivitySW and if the elapsed time crosses a day. If you don't do this, the button state changes only if user restarts the activity either by restarting the app or navigating to other activity and navigating back to ShareDetailActivitySW.

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