如何立即运行后台进程

时间:2017-03-08 19:27:19

标签: android android-asynctask android-progressbar

我正在开发一个应用程序,其中包括预先进行端口扫描。我的问题是我正在尝试在扫描发生时实现进度条。现在我使用AsynTask来执行扫描。但是,如何在扫描执行时更新进度条?我可以为这两个任务使用相同的AsynTask,或者我需要实现一个单独的任务。任何帮助欣赏! PortScanActivity

package com.example.android.droidscanner;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;

/**
 * Created by jlvaz on 3/7/2017.
 */

public class PortScanActivity extends AppCompatActivity{

    String ipAddress;
    ArrayList<String> openPorts;
    ArrayAdapter<String> portAdapter;
    int startPort = 0;
    int endPort = 1023;
    TextView statusMsg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_list);

        Intent portIntent = getIntent();
        ipAddress = portIntent.getStringExtra("host");

        statusMsg = (TextView) findViewById(R.id.status_msg);

        //setting the adapter
        ListView portList = (ListView) findViewById(R.id.scan_list);
        openPorts = new ArrayList<>();
        portAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, openPorts);
        portList.setAdapter(portAdapter);

        //scanning ports
        PortScanTask portScan = new PortScanActivity.PortScanTask();
        portScan.execute();

    }

    private class PortScanTask extends AsyncTask<Void, String, Void> {

        int timeOut = 1000; //for how long try connection in ms

        @Override
        protected void onPreExecute() {
            openPorts.clear();
            statusMsg.setText("Scanning " + ipAddress + " ports..");
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = startPort; i <= endPort; i++) {
                try {
                    //establishing connection to every port
                    Socket socket = new Socket();
                    SocketAddress address = new InetSocketAddress(ipAddress, i);
                    socket.connect(address, timeOut);
                    Log.v("Connecting to: ", ipAddress + i);
                    if (socket.isConnected()) {
                        socket.close();
                        publishProgress(ipAddress + ": " + i);
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                } catch (ConnectException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            openPorts.add(values[0]);
            portAdapter.notifyDataSetInvalidated();
            Toast.makeText(getApplicationContext(), values[0].toString() + " open!", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            statusMsg.setText("Scan Complete!");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在进度更新时,传递包含字符串和进度整数的自定义类对象。

class ProgressStep {
    int progress;
    String address;
}

private class PortScanTask extends AsyncTask<Void, ProgressStep, Void> {

    int timeOut = 1000; //for how long try connection in ms

    @Override
    protected void onPreExecute() {
        openPorts.clear();
        statusMsg.setText("Scanning " + ipAddress + " ports..");
    }

    @Override
    protected Void doInBackground(Void... params) {
        for (int i = startPort; i <= endPort; i++) {
            try {
                //establishing connection to every port
                Socket socket = new Socket();
                SocketAddress address = new InetSocketAddress(ipAddress, i);
                socket.connect(address, timeOut);
                Log.v("Connecting to: ", ipAddress + i);
                int progress = count_your_progress;
                ProgressStep step = new ProgressStep();
                step.progress = progress;
                if (socket.isConnected()) {
                    socket.close();
                    String address = ipAddress + ": " + i;
                    step.address = address;
                }
                publishProgress(step);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
            } catch (ConnectException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(ProgressStep... values) {
        ProgressStep step = values[0];
        if (step.address != null) {
            openPorts.add(step.address);
            portAdapter.notifyDataSetInvalidated();
            Toast.makeText(getApplicationContext(), step.address + " open!", Toast.LENGTH_SHORT).show();
        }

        progressBar.setProgress(step.progress);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        statusMsg.setText("Scan Complete!");
    }
}