Android 后台运行计时器

Android 后台运行计时器,android,service,timer,Android,Service,Timer,我有一个计时器,但我希望它也在后台运行,我创建了一个新的服务,我认为它可以工作,但我有一个问题,我还想更改布局属性,比如使用setText方法更改TextView文本,我更喜欢使用BroadCastReceiver执行此操作,因此我有以下代码: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.lay

我有一个计时器,但我希望它也在后台运行,我创建了一个新的
服务
,我认为它可以工作,但我有一个问题,我还想更改
布局
属性,比如使用
setText
方法更改
TextView
文本,我更喜欢使用
BroadCastReceiver
执行此操作,因此我有以下代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textView);
    IntentFilter filter = new IntentFilter();
    filter.addAction("SOME_ACTION");
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            textView.setText("hey");
        }
    };
    registerReceiver(receiver, filter);
    buttonStart = (Button) findViewById(R.id.start);
    buttonStart.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(MainActivity.this, LocalService.class));
        }
    });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}
我在这里注册了
接收器
,因此当我从
服务
进行广播时会发生这种情况,并将文本更改为“嘿”-我只是想检查广播是否正常。在
服务上
我使用了一个运行计时器的代码,当它启动时,它将广播消息,这是我第一次使用
广播接收器
发送
操作
,而不仅仅是等待
蓝牙
打开之类的东西,这是我的
服务
代码:

public class LocalService extends Service
{
    private static Timer timer = new Timer();

    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    public void onCreate()
    {
        super.onCreate();
        startService();
    }

    private void startService()
    {
        timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
    }

    private class mainTask extends TimerTask
    {
        public void run()
        {
            Intent intent = new Intent();
            intent.setAction("SOME_ACTION");
            sendBroadcast(intent);
        }
    }

    public void onDestroy()
    {
        super.onDestroy();
    }
}

谢谢您的帮助。

我在您的帖子中没有看到任何问题,但是您为什么不绑定到服务以获取计时器值呢?发送广播非常昂贵。@JonTom我的问题是为什么textView没有改变,oops:P为什么这段代码不起作用,我不明白绑定到服务以获取计时器值是什么意思。请看一下关于绑定服务的文档:。您可以绑定到活动的onCreate中的服务,将活动作为侦听器传递给该服务,并直接从服务调用活动的方法,而无需进行广播。如果您仍然希望使用BroadcastReceiver,我建议使用LocalBroadcastManager。本地广播仅限于应用程序的进程,因此更高效。这里给出的例子是:@JonTom非常感谢!