Android的服务多线程 [英] Android Service with multiple Threads

查看:112
本文介绍了Android的服务多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成立了一个ListView。每个在ListView项包含一个切换按钮,
这将启动或在服务停止线程。

I've set up a ListView. Each of the ListView-Items contains a ToggleButton, which starts or stops a Thread in a Service.

的线程需要只要的ToggleButtons被激活运行。如果活动停止,服务和激活的线程需要继续

The threads need to run as long as the toggleButtons are activated. If the activity stops, the service and the activated threads need to continue.

//In MainActivity
@Override
public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
Intent intent = new Intent(context,MyService.class);
intent.putExtra("id",listviewPosition);
startService(intent);
}


//MyService
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Thread(startId) starten
    HandlerThread thread = new HandlerThread(String.valueOf(startId));
    thread.start();
    // Threads looper holen und beim servicehandler benutzen
    serviceHandler = new ServiceHandler(thread.getLooper());
    listServericeHandler.add(serviceHandler);
    //message ausm pool holen
    Message msg = serviceHandler.obtainMessage();
    msg.arg1 = startId;
    serviceHandler.sendMessage(msg);
    return START_STICKY;
}

private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
    super(looper);
    }

@Override
public void handleMessage(Message msg) {
while (continueUntilToggleButtonIsDeactivated) {
Log.d(MainActivity.TAG, "Thread " + tring.valueOf(msg.arg1)
                + " running: " + url.toExternalForm());
synchronized (this) {
        try {
            //do stuff
            wait(1000);
        } catch (Exception e) {
        }
        }
    }
}
}

所以,我想我开始激活切换按钮的 OnStartCommand()每次在一个线程中。

我不知道如何停止线程,并获得了while循环的。

What I don't know is how to stop the threads and get the out of the while-loop.

推荐答案

您只需要创建while循环一个标志,遵守知道什么时候停下来。例如:

You just need to create a flag for the while loop to abide by to know when to stop. For example:

private final class ServiceHandler extends Handler {
    private volatile boolean _continueRunning = true;

    public ServiceHandler(Looper looper) {
        super(looper);
    }

    public void stopRunning() {
        _continueRunning = false;
        this.notify(); //Interrupts the wait
    }

    @Override
    public void handleMessage(Message msg) {
        while (_continueRunning) { //Watches the variable
            Log.d(MainActivity.TAG, "Thread " + tring.valueOf(msg.arg1)
                                + " running: " + url.toExternalForm());

        synchronized (this) {
            try {
                //do stuff
                wait(1000);
            } catch (Exception e) {}
        }
    }
}

修改

您应该建立在服务的的onCreate()方法您的处理程序。在 onStartCommand 方法会通知您的新邮件。

You should create your handler in the onCreate() method of the service. The onStartCommand method informs you of new messages.

//In your Service Class
...
private ServiceHandler _serviceHandler;

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceClassName");
    thread.start();

    // Threads looper holen und beim servicehandler benutzen
    serviceHandler = new ServiceHandler(thread.getLooper());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //message ausm pool holen
    Message msg = _serviceHandler.obtainMessage();
    msg.arg1 = startId;
    serviceHandler.sendMessage(msg);
    return START_STICKY;
}

private class mRunnable implements Runnable {
    private volatile boolean _continueRunning = true;

    @Override
    public void run() {
        while (_continueRunning) { //Watches the variable
            synchronized (this) {
                try {
                    //do stuff
                    wait(1000);
                } catch (Exception e) {
                    //Purposefully left blank
                }
            }
        }
    }

    public void stopRunning() {
        _continueRunning = false;
        this.notify();
    }
}

然后你改变你的ServiceHandler为

Then you change your ServiceHandler to

private final class ServiceHandler extends Handler {
    //TODO whatever type of list you need
    private List<mRunnable> _runningThreads = new LinkedList<mRunnable>();

    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        mRunnable runnable = new mRunnable();
        new Thread(runnable).start();
    }
}

这篇关于Android的服务多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆