添加进度条或进度对话以发送和接收文件

时间:2017-07-25 08:29:45

标签: android android-progressbar

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

接收者活动

 string WrapText(string statement, int Length)
        {            
            StringBuilder completedWord = new StringBuilder();

            completedWord.Append(statement.Substring(0, Length));//cut the specifed legth from long string
            completedWord.AppendLine();
            completedWord.Append(statement.Substring(Length));//read remainig letters
            return completedWord.ToString();
        }

接收者线程

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;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在活动中添加一个简单的ProgressDialog框。

类似的东西:

// 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;

您还可以拥有一个包含进度百分比的对话框。请查看ProgressDialog文档。

setProgressStyle(int style)等方法的值类似STYLE_HORIZONTAL。然后有incrementProgressBy(int diff)可以用来获得横条。