Android 添加用于发送和接收文件的进度条或进度对话框

Android 添加用于发送和接收文件的进度条或进度对话框,android,android-progressbar,Android,Android Progressbar,我已经实现了一个文件共享项目。我可以发送和接收文件,但想添加进度条或进度对话,但我不知道在哪里添加进度条 接收器活动 public class ReceiverActivity extends AppCompatActivity { FileReceiver fileReceiver; ImageButton ibt; private final Handler mHandler = new Handler(Looper.getMainLooper()) {

我已经实现了一个文件共享项目。我可以发送和接收文件,但想添加进度条或进度对话,但我不知道在哪里添加进度条

接收器活动

public class ReceiverActivity extends AppCompatActivity {

    FileReceiver fileReceiver;
    ImageButton ibt;

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
             /*   case FileReceiver.CODE :
                    tvCode.setText((int)msg.obj + "");
                    break;
*/
                case FileReceiver.LISTENING :
                    Toast.makeText(ReceiverActivity.this,"Listening...",Toast.LENGTH_SHORT).show();
                    break;

                case FileReceiver.CONNECTED:
                    Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
                    break;

                case FileReceiver.RECEIVING_FILE :
                    Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();
                    break;

                case FileReceiver.FILE_RECEIVED :
                    File file = (File) msg.obj;
                    Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
                    Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
                    fileReceiver.close();
                    break;

                case FileReceiver.RECEIVE_ERROR :
                    Toast.makeText(ReceiverActivity.this,"Error occured : " + (String)msg.obj,Toast.LENGTH_SHORT).show();
                    fileReceiver.close();
                    break;
            }
        }
    };

    public void getFile(View view) {

        fileReceiver = new FileReceiver(this,mHandler);

        fileReceiver.getFile();

    }

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

        ibt= (ImageButton) findViewById(R.id.imgbtn);
        ibt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ReceiverActivity.this, Selection_Activity.class);
                startActivity(i);
            }
        });


    }
}
接收线

public class ReceiverThread extends Thread {

    private int port;
    private Messenger messenger;
    private ServerSocket listenerSocket;
    private Socket communicationSocket;
    private int PKT_SIZE = 60*1024;
    ProgressDialog dialog;
    public ReceiverThread(int port,Messenger messenger){

//



        this.port = port;
        this.messenger = messenger;
        File folder = new File(Environment.getExternalStorageDirectory() + "/FileSharer/");

        folder.mkdirs();
    }

    @Override
    public void run() {

        Message message;

        try {
            listenerSocket = new ServerSocket(port);

            message = Message.obtain();
            message.what = FileReceiver.CODE;
            message.obj = port;
            messenger.send(message);

            message = Message.obtain();
            message.what = FileReceiver.LISTENING;
            message.obj = "";
            messenger.send(message);

            communicationSocket = listenerSocket.accept();

            message = Message.obtain();
            message.what = FileReceiver.CONNECTED;
            message.obj = "";
            messenger.send(message);


            DataInputStream in = new DataInputStream(communicationSocket.getInputStream());

            message = Message.obtain();
            message.what = FileReceiver.RECEIVING_FILE;
            message.obj = "";
            messenger.send(message);

            // Read File Name and create Output Stream
            String fileName = in.readUTF();

            File receiveFile = new File(Environment.getExternalStorageDirectory() + "/FileSharer/" + fileName);

            DataOutputStream dout = new DataOutputStream(new FileOutputStream(receiveFile,true));

            // Read File Size
            long fileSize = in.readLong();

            int totalLength = 0;
            int length = 0;
            byte[] receiveData = new byte[PKT_SIZE];

            long startTime = System.currentTimeMillis();

            // Get the file data
            while( fileSize>0 && ( ( length = in.read( receiveData,0,(int) Math.min(receiveData.length,fileSize) ))!= -1) )
            {
                dout.write(receiveData, 0, length);

                totalLength += length;

                fileSize -= length;
            }

            long stopTime = System.currentTimeMillis();

            dout.close();

            double time = (stopTime - startTime) / 1000.0;

            double speed = (totalLength / time) / 1048576.0;

            message = Message.obtain();
            message.what = FileReceiver.FILE_RECEIVED;
            message.obj = receiveFile;

            messenger.send(message);

        } catch (Exception e){

            e.printStackTrace();

            message = Message.obtain();
            message.what = FileReceiver.RECEIVE_ERROR;
            message.obj = e.toString();

            try {
                messenger.send(message);
            } catch (RemoteException re) {
                Log.e("ReceiverThread","Error in sending an error message! Error : " + re.toString());
                re.printStackTrace();
            }

        } finally {

            try {

                if(communicationSocket!=null)
                    communicationSocket.close();

                if(listenerSocket!=null)
                    listenerSocket.close();

            } catch (IOException ioe) {
                Log.e("ReceiverThread","Error in closing sockets. Error : " + ioe.toString());
                ioe.printStackTrace();
            }
        }

    }
}
接收服务

public class ReceiverService extends Service {

    private final String PORT = "PORT";
    private final String MESSENGER = "MESSENGER";

    private int port;
    private Messenger messenger;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Bundle b = intent.getExtras();

        port = (int) b.get(PORT);
        messenger = (Messenger) b.get(MESSENGER);

        ReceiverThread receiverThread = new ReceiverThread(port,messenger);

        receiverThread.start();

        return START_REDELIVER_INTENT;

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
文件接收器

public class FileReceiver {

    private final boolean mDebug = true;

//    private final int MIN_PORT_NUMBER = 1024;
  //  private final int MAX_PORT_NUMBER = 65536;
    private final String PORT = "PORT";
    private final String MESSENGER = "MESSENGER";

    // Constants start from 2001
    public static final int CODE = 2001;
    public static final int LISTENING = 2002;
    public static final int CONNECTED = 2003;
    public static final int RECEIVING_FILE = 2004;
    public static final int FILE_RECEIVED = 2005;
    public static final int RECEIVE_ERROR = 2006;

    private Context context;
    private Handler mHandler;

    private Intent i;

    public FileReceiver(Context context, Handler mHandler) {
        this.context = context;
        this.mHandler = mHandler;
    }

/*    private boolean isPortAvailable(int port) {

        boolean available;

        if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
            throw new IllegalArgumentException("Invalid port: " + port);
        }

        ServerSocket ss = null;

        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            available = true;
        } catch (IOException e) {
            available = false;
        } finally {

            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {

                }
            }
        }

        return available;
    }
*/
    private int getRandomPort() {
 //int port = 1001;
        int port = 40500;

        //do{
          //  port = (int) (MIN_PORT_NUMBER + 1 + Math.floor(Math.random()*(MAX_PORT_NUMBER - MIN_PORT_NUMBER-1)));

            if(mDebug)
                Log.i("FileReceiver","Trying port : " + port);

//        }while(!isPortAvailable(port));

        return port;


 //   return port;
    }

    public void getFile(){

        int port = getRandomPort();

        if(mDebug)
            Log.i("FileReceiver","Port : " + port);

        i = new Intent(context,ReceiverService.class);

        i.putExtra(PORT,port);
        i.putExtra(MESSENGER,new Messenger(mHandler));

        context.startService(i);

    }

    public void close() {
        context.stopService(i);
    }
}
公共类FileReceiver{
私有最终布尔值mDebug=true;
//专用最终整数最小端口号=1024;
//专用最终int最大端口号=65536;
专用最终字符串PORT=“PORT”;
专用最终字符串MESSENGER=“MESSENGER”;
//从2001年开始
公共静态最终整数代码=2001;
公共静态最终听力=2002年;
公共静态最终int CONNECTED=2003;
公共静态最终int接收_文件=2004;
公共静态最终int文件_已接收=2005;
公共静态最终int接收错误=2006;
私人语境;
私人经理人;
私人意图一;
公共FileReceiver(上下文,处理程序mHandler){
this.context=上下文;
this.mHandler=mHandler;
}
/*专用布尔值isPortAvailable(int端口){
布尔值可用;
如果(端口<最小端口号>最大端口号){
抛出新的IllegalArgumentException(“无效端口:+端口”);
}
ServerSocket ss=null;
试一试{
ss=新服务器套接字(端口);
ss.setReuseAddress(正确);
可用=真实;
}捕获(IOE异常){
可用=错误;
}最后{
如果(ss!=null){
试一试{
ss.close();
}捕获(IOE异常){
}
}
}
返回可用;
}
*/
私有int getRandomPort(){
//int端口=1001;
int端口=40500;
//做{
//端口=(int)(最小端口号+1+数学地板(数学随机()*(最大端口号-最小端口号-1));
如果(mDebug)
Log.i(“FileReceiver”,“尝试端口:”+端口);
//}而(!isPortAvailable(port));
返回端口;
//返回端口;
}
public void getFile(){
int-port=getRandomPort();
如果(mDebug)
Log.i(“文件接收器”,“端口:”+端口);
i=新意图(上下文,ReceiverService.class);
i、 putExtra(港口,港口);
i、 putExtra(信使、新信使(mHandler));
启动服务(一);
}
公众假期结束(){
停止服务(一);
}
}

您可以从活动中添加一个简单的
进度对话框

比如:

// global variable 
ProgressDialog mProgressDialog;

...
...

// inside onCreate
mProgressDialog = new ProgressDialog(ReceiveActivity.this);
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage("Downloading file ..");

...
...

// before file downloads
mProgressDialog.show();

...
...

// when file is downloaded
mProgressDialog.dismiss();
编辑:

对于给定的问题,可以通过以下方式进行:

// assuming mProgressDialog is already initialised and configured.

          case FileReceiver.CONNECTED:
                Toast.makeText(ReceiverActivity.this,"Connected!",Toast.LENGTH_SHORT).show();
                /******** Show the dialog box *********/
                mProgressDialog.show(); // make sure that the file receiving starts immediately
                                        // after the receiver is connected and that it do not
                                        // require any action (like button click) after is connected

                break;

            case FileReceiver.RECEIVING_FILE :
                Toast.makeText(ReceiverActivity.this,"Receiving File!",Toast.LENGTH_SHORT).show();

                /******** Dismiss the dialog box *********/
                mProgressDialog.dismiss();
                break;

            case FileReceiver.FILE_RECEIVED :
                File file = (File) msg.obj;
                Toast.makeText(ReceiverActivity.this,file.getName() + " Received!",Toast.LENGTH_SHORT).show();
                Toast.makeText(ReceiverActivity.this,"Stored in " + file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
                fileReceiver.close();

                /******** Dismiss the dialog box *********/
                mProgressDialog.dismiss();
                break;
您还可以有一个带有进度百分比的对话框。查看文档


有像
setProgressStyle(int-style)
这样的方法,其值像
style\u HORIZONTAL
。然后有
incrementProgressBy(int diff)
可以用来在那里获得一个水平条。

对于我来说,进度对话框是做你想做的事情的最佳选择。具体来说,我应该在上面发布的接收器活动中放置进度条的代码,因为下载/接收有四个部分,接收器活动、接收器线程、接收器服务和文件接收器这可能位于
接收器活动中的
开关(){}
show()
FileReceiver的
case
中显示进度框。已连接
解除()
FileReceiver.FILE的
case
中显示进度框。已收到
FileReceiver.RECEIVE\u ERROR
非常感谢,但我想知道是否可以在进度对话框中显示百分比??