android 开启服务进行FTP上传,上传进度在通知栏显示

1.定义广播类,用来接收进度信息,并将信息传递给通知栏中的进度条

package com.screening.uitls;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.application.MyApplication;
import com.screening.activity.AdminSetActivity;
import com.screening.model.Area;
import com.screening.model.Bean;
import com.screening.model.Const;
import com.util.ToastUtils;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;

public class UpDateBroadcastReceiver extends BroadcastReceiver {
    private static final int notifyId=10;
    @Override
    public void onReceive(Context context, Intent intent) {
        double progress=intent.getDoubleExtra("progress",0);
        Const.getOneItem().getNotificationUtils().updateProgress(notifyId,(int)progress);
        if(progress==100){
//            bt_commit.setEnabled(true);
            ToastUtils.showToast(context,"上传已完成");
            Const.getOneItem().setNotificationUtils(null);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<Area> areaList= DataSupport.findAll(Area.class);
                    File file=new File(Bean.bePath+areaList.get(0).getCommunity());
                    if(file.exists()){
                        new Deleteutils().deleteLocal(file);
                    }
                }
            }).start();
        }
    }
}

2.使用静态广播(静态广播在程序推出后,后台还在运行时还可以接收到广播信息)

配置文件注册广播:


定义广播权限:

<permission android:name="com.screen.permission.RECEIVER" />

<uses-permission android:name="com.screen.permission.RECEIVER" />

3.定义服务类,在该类中进行上传和广播通知

package com.screening.service;


import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.screening.activity.AdminSetActivity;
import com.screening.model.Area;
import com.screening.model.Bean;
import com.screening.model.FTPPath;
import com.screening.uitls.CopyUtils;
import com.screening.uitls.Deleteutils;
import com.screening.uitls.LogWriteUtils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.TimeZone;

public class UpLoadService extends Service {
    private FTPClient ftpClient;//FTP连接
    private String strIp="";//ip地址
    private int intPort=;//端口号
    private String user="";//用户名
    private String password="";//用户密码
    private long LocalAllSize,FTPAllSize;
    public UpLoadService(){
        ftpClient=new FTPClient();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new  uploadTAsk().execute("");
        return super.onStartCommand(intent, flags, startId);
    }
    private class uploadTAsk extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            Deleteutils deleteutils=new Deleteutils();
            List<Area> areaList = DataSupport.findAll(Area.class);
            if (areaList.size() > 0) {
                String path = "";
                if (areaList.get(0).getCommunity() == null) {
                    path = Bean.bePath + "default";
                } else {
                    path =Bean.bePath + areaList.get(0).getCommunity();
                }
                File file=new File(path);//某次筛查的全部文件,即根目录,如100
                if (file.exists()) {
                    int temp=deleteutils.fileIsNull(file);
                    if(temp==0){
                        boolean isSuccess = ftpLogin();
                        if (isSuccess) {
                            boolean a = uploadDirectory(path, "/");
                            if (a) {
                                ftpLogOut();
                                FTPAllSize=0;
                                LocalAllSize=0;
                                path="";
                            } else {
                            }
                        }
                    }else {
                        deleteutils.deleteLocal(file);
                    }

                }

            }
            return null;
        }

    }

    /***
     * @上传文件夹
     * @param localDirectory
     *   当地文件夹
     * @param remoteDirectoryPath
     *   Ftp 服务器路径 以目录"/"结束
     * */
    boolean makeDirFlag=false;
    public boolean uploadDirectory(String localDirectory,
                                   String remoteDirectoryPath) {
        File src = new File(localDirectory);

        try {
            initCreateFtpFile(remoteDirectoryPath);
            initCreate(localDirectory);
        }catch (Exception e) {
//            e.printStackTrace();
            Log.e("is",e.getMessage().toString());
        }
        if(makeDirFlag){
            File[] allFile = src.listFiles();
            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    String srcName = allFile[currentFile].getPath().toString();
                    uploadFile(new File(srcName), remoteDirectoryPath);
                }
            }
            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    // 递归
                    uploadDirectory(allFile[currentFile].getPath().toString(),
                            remoteDirectoryPath);
                    initCopy(allFile[currentFile].getPath().toString());
                }
            }
            return makeDirFlag;
        }else {
            ftpLogOut();
            return makeDirFlag;
        }
    }
    /***
     * 上传Ftp文件
     * @param localFile 当地文件
     * @param
     * */
    int num=0;
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            Log.e("logging",localFile.getName() + "开始上传.....");
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            //文件上传成功
            if (success == true) {
                num=0;
               initSize(romotUpLoadePath,localFile);
                //将已上传数据的百分比传递给广播,实现ui界面的更新
                double percent=((double)FTPAllSize/LocalAllSize)*100;
                Intent intent=new Intent("android.screen.update.PROGRESS");
//                intent.setAction("android.screen.update.PROGRESS");
                intent.putExtra("progress",percent);
                sendBroadcast(intent,"com.screen.permission.RECEIVER");
                //文件上传成功后复制到新的目录
                int temp=initCopy(localFile.getAbsolutePath());
                //文件复制成功后,删除原始文件
                if(temp==-1){
                }else {
//                    initDelete(localFile.getAbsolutePath());
                }
                List<Area>areaList=DataSupport.findAll(Area.class);
                String sc= Bean.bePath+areaList.get(0).getCommunity();
                new Deleteutils().fileIsNull(new File(sc));
                return success;
            }else {//文件上传失败后,再次进行上传,最多上传4次
                if(num<=3){
                    uploadFile(localFile,romotUpLoadePath);
                }else {
                    LogWriteUtils.e("上传失败图片",localFile.getAbsolutePath());
                }
                num++;
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inStream != null) {
                try {
                    inStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
    //创建服务器文件
    private void initCreateFtpFile(String remoteDirectoryPath){
        //遍历该服务器某级目录下所有文件的集合
        FTPFile[]ftpFiles= new FTPFile[0];
        try {
            ftpFiles = ftpClient.listFiles(remoteDirectoryPath);
            if(ftpFiles.length==0){
                makeDirFlag= this.ftpClient.makeDirectory(remoteDirectoryPath);//在ftp服务器上创建文件
            }else {
                makeDirFlag=true;
            }
            if(!makeDirFlag){
                if(num<=3){
                    initCreateFtpFile(remoteDirectoryPath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //得到服务器文件大小,刚刚上传成功的,如果上传成功,但是该文件的大小没有计入总大小,则重复进行计算
    private void initSize(String path,File localFile){
        FTPFile []ftpFiles= new FTPFile[0];
        try {
            ftpFiles = ftpClient.listFiles(path+localFile.getName());
            if(ftpFiles.length>0){
                FTPAllSize+=ftpFiles[0].getSize();
                Log.e("loadSuccess",localFile.getName() + "上传成功"+FTPAllSize);
            }else {
                if(num<=3){
                    initSize(path,localFile);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //文件复制成功后删除原始文件
    private void initDelete(String path){
        new File(path).delete();
    }
    //创建复制的目标目录
    private void initCreate(String filePath){
        String []path=filePath.split("/");
        String toMir=Bean.endPath;
        if(path.length>=4){
            for(int i=5;i<path.length;i++){
                toMir+=path[i]+"/";
            }
        }
        File file=new File(toMir);
        if(!file.exists()){
            file.mkdirs();
        }
    }
    //每次上传成功后开始复制文件
    private int initCopy(String filePath){
        String []path=filePath.split("/");
        String toDir=Bean.endPath;
        if(path.length>=4){
            for(int i=5;i<path.length-1;i++){
                toDir+=path[i]+"/";
            }
            toDir+=path[path.length-1];
        }
       int temp= new CopyUtils().copyFile(filePath,toDir);
        return temp;
    }
    /**
     * @退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                    Log.e("success","成功退出服务器");
                }
            }catch (IOException e) {
                e.printStackTrace();
                Log.e("success","退出FTP服务器异常!" + e.getMessage());
            }finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                }catch (IOException e) {
                    e.printStackTrace();
                    Log.e("success","关闭FTP服务器的连接异常!");
                }
            }
        }
    }
    /**
     * @return 判断是否登入成功
     * */
    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        ftpClient.setControlEncoding("utf-8");
        ftpClient.configure(ftpClientConfig);
        try {
            if (this.intPort > 0) {
                ftpClient.connect(this.strIp, this.intPort);
            }else {
                ftpClient.connect(this.strIp);
            }
            // FTP服务器连接回答
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                Log.e("faild","登录FTP服务失败!");
                return isLogin;
            }
            ftpClient.login(this.user, this.password);
            // 设置传输协议
//            this.ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            Log.e("faild","恭喜" + this.user + "成功登陆FTP服务器");
            isLogin = true;
        }catch (Exception e) {
            e.printStackTrace();
            Log.e("faild",this.user + "登录FTP服务失败!" + e.getMessage());
        }
        ftpClient.setBufferSize(1024 * 2);
        ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }
  
    /**
     * 本地文件大小
     */
    public long getSize(File [] localFile){

        for(int i=0;i<localFile.length;i++){
            if(localFile[i].isFile()){
                LocalAllSize+=localFile[i].length();
            }else {
                getSize(localFile[i].listFiles());
            }
        }
        return LocalAllSize;
    }
}

3.定义通知栏

package com.screening.uitls;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

import com.activity.R;
import com.screening.activity.MainActivity;

import java.util.HashMap;
import java.util.Map;

public class NotificationUtils {
    private Context context;
    //状态栏通知的管理类,复制发通知,清除通知等
    private NotificationManager manager;
    //定义Map来保存Notification对象
    private Map<Integer,Notification>map=null;
    public NotificationUtils(Context context){
        this.context=context;
        //notificationmanager是一个系统service,必须通过getSystemService()发方来得到
        manager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        map=new HashMap<Integer, Notification>();
    }
    public void showNotification(int notificationId){
        //判断对应id的notification是否已经显示,以免同一个notification出现多次
        if(!map.containsKey(notificationId)){
            //创建通知对象
            Notification notification=new Notification();
            //设置通知栏滚动显示文字
            notification.tickerText="开始上传数据";
            //设置显示时间
            notification.when=System.currentTimeMillis();
            //设置通知显示的图标
            notification.icon= R.drawable.a3;
            //设置通知的特性:通知被点击后,自动消失
            notification.flags=Notification.FLAG_AUTO_CANCEL;
            //设置点击通知栏操作
//            Intent intent=new Intent(context, MainActivity.class);//点击跳转到指定页面
//            PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent,0);
//            notification.contentIntent=pendingIntent;
            //设置通知的显示视图
            RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.progress);
//            //设置暂停按钮的点击事件
//            Intent pause=new Intent(context,MainActivity.class);//设置跳转到对应页面
//            PendingIntent pauseIn=PendingIntent.getActivity(context,0,intent,0);
//            //这里可以通过Bundle等传递参数
//            remoteViews.setOnClickPendingIntent(R.id.pause,pauseIn);
//           // 设置取消按钮的点击事件
//            Intent stop=new Intent(context,MainActivity.class);//设置跳转到对应页面
//            PendingIntent stopIn=PendingIntent.getActivity(context,0,intent,0);
//            //这里可以通过Bundle等传递参数
//            remoteViews.setOnClickPendingIntent(R.id.cancel,stopIn);
            //设置显示进度

            //设置通知的显示试图
            notification.contentView=remoteViews;
            //发出通知
            manager.notify(notificationId,notification);
            map.put(notificationId,notification);
        }

    }
    //取消通知操作
    public void cancel(int notificationId){
        manager.cancel(notificationId);
        map.remove(notificationId);
    }
    //修改进度条
    public void updateProgress(int notificationId,int progress){
        Notification notification=map.get(notificationId);
        if(notification!=null){
            notification.contentView.setProgressBar(R.id.pBar,100,progress,false);
            if(progress<100){
                notification.contentView.setTextViewText(R.id.tv_pro,progress+"%");
            }else {
                notification.contentView.setTextViewText(R.id.tv_pro,"上传已完成");
            }
            manager.notify(notificationId,notification);
        }
    }
}
自定义通知栏布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文件上传"
        android:textColor="@color/white"
        android:textSize="15dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <ProgressBar
            android:id="@+id/pBar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_weight="1" />
        <TextView
            android:id="@+id/tv_pro"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:textSize="15dp"
            android:textColor="@color/white"/>
        <!--<Button-->
            <!--android:id="@+id/pause"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="30dp"-->
            <!--android:layout_weight="2"-->
            <!--android:text="暂停" />-->

        <!--<Button-->
            <!--android:id="@+id/cancel"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="30dp"-->
            <!--android:layout_weight="2"-->
            <!--android:text="取消" />-->
    </LinearLayout>

</LinearLayout>

至此项目完结,可以使用不同的传输方式,原理都是开启服务进行耗时操作,广播监听进度,然后开启自定义通知栏,显示进度。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值