Android长期背景线程

时间:2015-04-09 04:32:15

标签: android multithreading

我是一名编写我的第一个Android应用程序的程序员。

在C#中,我通常使用Thread Worker类来实现我想要实现的目标。

应用程序包含一组文本框,我需要根据类中的变量每秒更新一次。我希望能够启动一个后台线程,其中包含一个进行更新的循环。

我正在使用的代码如下所示。 如果我退出循环,我可以完成一次更新,但如果我不这样做,GUI就会变得没有响应(锁定)。我假设代码没有在后台运行。 目前我正在尝试使用Runnable,但可能会查看AsyncTask甚至Executor。

package com.example.redkatipo.myfirstapp;

import android.os.*;

import java.util.List;

/**
 * Created by Brian on 6/04/2015.
*/


class GroupTimerWorker implements Runnable {
Boolean _stopping = false;
Boolean _stopped = false;
Boolean _paused = false;
List<TimerLine> _lines;

public GroupTimerWorker(List<TimerLine> lines) {
    _lines = lines;
}

public void Stop() {
    _stopping = true;
}

public void SetPaused(Boolean pause) {
    _paused = pause;
}


@Override
public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUN    D);
    while (!_stopping) {
        try {
            Thread.sleep(1000);
            if (!_paused) {
                updateAllTimers();
            }
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
       _stopping = true;
    }

}




public synchronized void updateAllTimers() {

    for (int i = 0; i < _lines.size(); i++) {
        TimerLine tl = _lines.get(i);
        if (tl._isRunning) {
            tl.SetCurrentDuration();
        }
    }
}

}

public void updateAllTimers(View view) {
   _groupTimerWorker = new GroupTimerWorker(_displayLines);
   new Thread (_groupTimerWorker).run();


}


package com.example.redkatipo.myfirstapp;

import android.content.Context;
import android.os.SystemClock;
import android.content.res.Resources;
import android.text.method.BaseKeyListener;
import android.widget.TextView;
import android.widget.Button;

/**
 * Created by Brian on 27/03/2015.
 */

public class TimerLine {

public Context _context;
public Button _stopStart;
TextView _person;
public TextView _elapsed;
boolean _isRunning;

int _startTime = 0;
int _currentTime = 0;
int _previousTime = 0;

public TimerLine(Context context, Button _control, TextView _id, TextView _output) {
    _context = context;

    _stopStart = _control;

    _person = _id;
    _elapsed = _output;
    _isRunning = false;
    _stopStart.setTag(this);

    _elapsed.setText("idle");
}

private int CurrentSeconds()
{
    return (int)(SystemClock.uptimeMillis()/1000);
}

public void stopStartButtonClick()
{
    if (_isRunning == false) {
        _isRunning = true;
       // _stopStart.setBackground(_context.getResources().getDrawable(R.drawable.red_button));
        _stopStart.setText("Stop");

        _elapsed.setBackground(_context.getResources().getDrawable(R.drawable.green_button));
        _previousTime = _previousTime + _currentTime - _startTime;
        _elapsed.setText(formatTime(_previousTime));

        _startTime = CurrentSeconds();
    } else {
        _isRunning = false;
       /// _stopStart.setBackground(_context.getResources().getDrawable(R.drawable.green_button));
        _stopStart.setText("Start");
        _currentTime = CurrentSeconds();
        int difference = (_currentTime - _startTime);
        int totalTime = difference + _previousTime;
        _elapsed.setText(formatTime(totalTime));
        _elapsed.setBackground(_context.getResources().getDrawable(R.drawable.red_button));

    }

}

public void SetCurrentDuration()
{
    int now = CurrentSeconds();
    int difference = now - _startTime;
   int totalTime = difference + _previousTime;
    _elapsed.setText(formatTime(totalTime));
}

private String formatTime(int totalTime)
{
    int minutes = totalTime/60;
    int seconds = totalTime % 60;
    return "" + minutes + ":" + String.format("%02d", seconds);
}

}

1 个答案:

答案 0 :(得分:0)

在android中有几种方法可以做到这一点。但我更喜欢以下流程。

class Yourclass{
     Runnable mRunnable ;
     int x=1;//number of sec

     private void AnyFunction( ) {
        mRunnable = new Runnable() {
        @Override
        public void run() {
               <create a handler here say myhandler>
        //Optional if you want to start the first call af 'x' sec
             myhandler.postDelayed(mRunnable, x * 1000);
        }
    };

}
 private final Handler myhandler= new Handler() {


    @Override
    public void handleMessage(Message msg) {
          switch (msg.what) {
        case ans1:
             {
                <your code to change update ui etc>

                  myhandler.postDelayed(mRunnable, x * 1000);

               break;
             }

    }

   /*How to call this from any function wher you need to call the interval                     if oncreate the on creat call method AnyFunction*/

    AnyFunction();

}

希望这可能会有所帮助。