0

In my application, am try to set an time out function i not able to call the handler method in separate class.

My Timeout Class

 public class Timeout_function {

private Handler mHandler;
Activity activity;

public Timeout_function(Activity activity,Handler mHandler) {
    super();
    this.activity = activity;
    this.mHandler = mHandler;
}

Runnable myTask = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(activity, "Test", 1000).show();
        mHandler.postDelayed(this, 1000);
    }
};

// just as an example, we'll start the task when the activity is started
public void onStart() {
    mHandler.postDelayed(myTask, 1000);
}

// at some point in your program you will probably want the handler to stop
// (in onStop is a good place)
public void onStop() {

    mHandler.removeCallbacks(myTask);
}
}

Main class In main class i call the method in this way,but it shows error in run time,

Timeout_function timeout = new Timeout_function(this, mHandler);
    timeout.onStart();

how to call the method in main class.can any one know please help me to solve this problem.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Yugesh
  • 4,030
  • 9
  • 57
  • 97
  • What do you mean by "handler function", because your `mHandler` is an object. Also, why do you think you can't call it? Plus, what's your architecture? Where is the code called which is supposed to interact with the `Handler`? – class stacker Apr 30 '13 at 07:43
  • @ClassStacker how to start the interaction with handler. – Yugesh Apr 30 '13 at 07:47
  • I believe you have extracted this code from an Activity, where `onStart` would be called for you as part of the `Activity` lifecycle. It isn't doing this, so now you'll have to call `onStart` yourself. – David O'Meara Apr 30 '13 at 07:54

1 Answers1

0

Instead of creating a seperate class why you are not using Service?

I would insist you to use Service and start your Runnable using Handler in onStartCommand() of Service by call startService(intent);

and you can stop the Runnable using Handler by placing it inside onDestroy() method of Service and calling by stopService(intent).

This is what I had done and it works like a charm!

Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242