通过服务访问活动

时间:2013-01-07 07:47:56

标签: java android service android-activity

我有活动和服务。 该活动有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;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用意图将任何信息(即TextView成员的计数器)发送到活动。

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

...然后,您将使用广播接收器

在活动中接收您的数据
/**
 * 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));
    }
};