0

I have an Activity and a service. The activity has a TextView member and a setText() method. I would like to call that method through the Service, how can I do that? Here is the code:

Activity:

public class MainActivity extends Activity {
    private TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.tv1 = (TextView) findViewById(R.id.textView1);
        Intent intent = new Intent(this,MyService.class);
        startService(intent);
    }

    // <-- some deleted methods.. -->

    public void setText(String st) {
        this.tv1.setText(st);
    }
}

Service:

public class MyService extends Service {
    private Timer timer;
    private int counter;

    public void onCreate() {
        super.onCreate();
        this.timer = new Timer();
        this.counter = 0;
        startService();
    }

    private void startService() {
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                //MainActivityInstance.setText(MyService.this.counter); somthing like that
                MyService.this.counter++;
                if(counter == 1000)
                    timer.cancel();
            }
        },0,100);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
Imri Persiado
  • 1,857
  • 8
  • 29
  • 45
  • 1
    check this link: http://stackoverflow.com/questions/10783688/android-access-activity-method-inside-service – secretlm Jan 07 '13 at 08:05

1 Answers1

1

You can use an intent in order to send any information (i.e. the counter for TextView member) to the Activity.

public void run() {
    //MainActivityInstance.setText(MyService.this.counter); somthing like that
    MyService.this.counter++;
    Intent intentBroadcast = new Intent("MainActivity");
    intentBroadcast.putExtra("counter",MyService.this.counter);
    sendBroadcast(intentBroadcast);
    if(counter == 1000)
    timer.cancel();
}

...then, you will receive your data in the Activity using a Broadcast Receiver

/**
 * Declares Broadcast Reciver for recive location from Location Service
 */
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get data from intent
        serviceCounter = intent.getIntExtra("counter", 0);
        // Change TextView
        setText(String.valueOf(counterService));
    }
};
jgonza73
  • 344
  • 1
  • 10