Reputation: 685
I have a new problem. I am building an Android timer. In the main activity you can choose how long the timer will run. If you have chosen a value a timer activity should appear. My question is simple: How? I don't know how the timer activity can know how long the timer should run. Can anyone tell me please?
Upvotes: 0
Views: 119
Reputation: 30845
In the intent you use to start the new activity, put an extra that indicates the amount of time with which the Timer should be set. Let's say you've made an intent to start this timer activity called timeIntent
and the amount of time you want the timer to be set for is in a variable called amountOfTime
, they you'd do the following:
timerIntent.putExtra("time amount", amountOfTime);
startActivity(timerIntent);
One your in the timer activity, you can get this amount by calling getIntent()
and getExtra()
like so:
Intent myIntent = getIntent();
int timeAmount = 0;
if(myIntent!= null && myIntent.hasExtra("time amount"){
timeAmount = myIntent.getIntExtra("time amount", 0);
}
Upvotes: 3
Reputation: 6376
In your main activity, you'll want to put an extra into your intent for consumption by your timer activity:
Intent i = new Intent(this, TimerActivity.class);
i.putExtra("timer_length", 3000);
startActivity(i);
Then in your Timer Activity, you'll get the Intent's extras and do what you need with the passed in value:
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.timer_layout);
long length = getIntent().getLongExtra("timer_length", -1);
if (length == -1)
//do failure
else
//do what you need with the timer length value
}
Upvotes: 2