Skip to content

Instantly share code, notes, and snippets.

@shaxxx
Created November 21, 2014 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaxxx/b091cfbb8349d9f0ce29 to your computer and use it in GitHub Desktop.
Save shaxxx/b091cfbb8349d9f0ce29 to your computer and use it in GitHub Desktop.
Android Activity with runnable that accepts parameter and has callback
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button)findViewById(R.id.button1);
final EditText editText = (EditText)findViewById(R.id.editText1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vw) {
button.setText(new Date().toString());
editText.setText(new Date().toString());
Runnable runnable = new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
SystemClock.sleep(3000);
SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm:ss MM/dd/yyyy", Locale.US);
String dateString = dateformat.format(new Date());
bundle.putString("myArgument", dateString);
msg.setData(bundle);
handler.sendMessage(msg);
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
});
}
public void editText1Clicked(View v) {
EditText editText = (EditText)findViewById(R.id.editText1);
editText.setText(new Date().toString());
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
String argument = bundle.getString("myArgument");
EditText editText = (EditText)findViewById(R.id.editText1);
editText.setText(argument);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment