0

我有一个活动和一个服务。该活动有一个TextView成员和一个setText()方法。我想通过服务调用该方法,我该怎么做?这是代码:

活动:

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);
    }
}

服务:

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;
    }
}
4

1 回答 1

1

您可以使用意图将任何信息(即 TextView 成员的计数器)发送到 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();
}

...然后,您将使用广播接收器在 Activity 中接收数据

/**
 * 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));
    }
};
于 2013-01-07T08:06:52.840 回答