应用使用相关服务FTP

开发过程中会经常遇到需要保存一些信息到FTP服务器中,这个时候我们就需要调用三方jar来获取相关api来完成相关操作
1、libcommons_net_3.8.0.jar实现FTP文件文件上传下载及检测操作:
提供的api接口包括:

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

2、在Android.mk添加jar包方式
假如想在设置中添加FTP访问:
packages/apps/Settings/Android.mk

    telephony-ext

  LOCAL_STATIC_JAVA_LIBRARIES := \
+     libcommons_net_3.8.0 \
      android-arch-lifecycle-runtime \
      android-arch-lifecycle-extensions \
      guava \

  include $(BUILD_PACKAGE)

+ include $(CLEAR_VARS)
+ LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := libcommons_net_3.8.0:jars/commons-net-3.8.0.jar
+ include $(BUILD_MULTI_PREBUILT)

# Use the following include to make our test apk.
ifeq (,$(ONE_SHOT_MAKEFILE))
include $(call all-makefiles-under,$(LOCAL_PATH))

commons-net-3.8.0.jar包存放位置为:
packages/apps/Settings/jars/commons-net-3.8.0.jar
这个是和 Android.mk中LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := libcommons_net_3.8.0:jars/commons-net-3.8.0.jar添加方式有关

3、由于系统app没有获取网络的权限,这时就需要在packages/apps/Settings/AndroidManifest.xml中添加上网络访问权限:

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.TETHER_PRIVILEGED" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+   <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
+   <uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

4、接下来就是调用api与FTP服务器连接实现相应的访问代码实现:
packages/apps/Settings/src/com/android/settings/utils/GetConnectFtpFile.java下面代码是检测FTP上固定文件是否存在的实现方式

package com.android.settings.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.FileInputStream;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.os.SystemProperties;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import java.io.File;
import android.os.SystemProperties;
import java.io.FileOutputStream;
import java.io.InputStream;


public class GetConnectFtpFile {
	public static final String TAG = "GetConnectFtpFile";

    private static FTPClient mFTPClient = null;
	private TelephonyManager mTelephonyManager = null;
	private String mNeedUploadFile = null;
	private Context mContext;

    private String FTP_SERVER = "XXX.XXX.XX.XXX";
    private String FTP_USERNAME = "XXXXXX";
    private String FTP_PASSWORD = "XXXXX";
    private int FTP_PORT = 21;
    private String FTP_DIR ="/XXXXX/XXXX_devicesinfo";
	private String FTP_DIR_FILE ="/XXXXXXX/xts_test_file/test_file_123";
	private String mFileName = null;
	private boolean checkFileIsExist = false;

    //private Context context;
	
    public boolean ftpConnect(String host, String username, String password, int port) {
        try {
            mFTPClient = new FTPClient();
            Log.d(TAG,"ftpConnect() connecting to the ftp server " + host + ":" + port);
            mFTPClient.connect(host, port);

            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                Log.d(TAG,"login to the ftp server");
                boolean status = mFTPClient.login(username, password);
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();
                return status;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"Error: could not connect to host " + host);
        }
        return false;
    }

    public boolean ftpDisconnect() {
        if (mFTPClient == null) {
            return true;
        }

        try {
            mFTPClient.logout();
            mFTPClient.disconnect();
            mFTPClient = null;
            return true;
        } catch (Exception e) {
            Log.d(TAG,"Error occurred while disconnecting from ftp server.");
        }
        return false;
    }

    public boolean ftpChangeDir(String path) {
        boolean status = false;
        try {
            status = mFTPClient.changeWorkingDirectory(path);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"change directory failed: " + e.getLocalizedMessage());
        }
        return status;
    }
	
	public InputStream checking(String path) {
        InputStream is = null;
        try {
            is = mFTPClient.retrieveFileStream(path);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"change directory failed: " + e.getLocalizedMessage());
        }
        return is;
    }
	
	public void checkFile()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
				boolean connectResult = ftpConnect(FTP_SERVER, FTP_USERNAME, FTP_PASSWORD, FTP_PORT);
				if (connectResult) {		
					// 进入文件所在目录,注意编码格式,以能够正确识别中文目录
					//mFTPClient.changeWorkingDirectory(new String(dir.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));
					boolean changeDirResult = ftpChangeDir(FTP_DIR);

					// 检验文件是否存在
					//InputStream is = mFTPClient.retrieveFileStream();
					InputStream is = checking(FTP_DIR_FILE);
					if(is == null || mFTPClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
						checkFileIsExist = false;
						Log.d(TAG,"is == null  checkFileIsExist =="+checkFileIsExist);
						Log.d(TAG,"is == null || mFTPClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE");
						//return false;
					}
					if(is != null){
						checkFileIsExist = true;
						Log.d(TAG,"is != null!!! checkFileIsExist =="+checkFileIsExist);
						ftpDisconnect();
						//return true;
					}
				}else {
					checkFileIsExist = false;
				}
				//return false;
			}
        }).start();
    }
	
	public boolean checkFileIsExist(){
		try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
		Log.d(TAG,"checkFileIsExist = "+checkFileIsExist);
		return checkFileIsExist;
	}
}

上传文件到FTP服务器方式:

package com.xxxxx.xxxx.xxxx.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.FileInputStream;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.os.SystemProperties;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import java.io.File;
import com.qualcomm.qti.qmmi.testcase.Sim.SimService;
import android.os.SystemProperties;
import java.io.FileOutputStream;


public class DeviceInfoToFTP {
	public static final String TAG = "DeviceInfoToFTP";

    private static FTPClient mFTPClient = null;
	private TelephonyManager mTelephonyManager = null;
	private String mNeedUploadFile = null;
	private Context mContext;

    private String FTP_SERVER = "xxx.xxx.xxx.xxx";
    private String FTP_USERNAME = "xxxx";
    private String FTP_PASSWORD = "xxxxx";
    private int FTP_PORT = 21;
    private String FTP_DIR ="/xxxx/xxxx_devicesinfo";
	private String mFileName = null;

    //private Context context;
	
    public DeviceInfoToFTP(Context context) {
        // We used to store the saved images in the cache directory, but that meant they'd get
        // deleted sometimes-- move them to the data directory
        mContext = context;
    }
	
    public boolean ftpConnect(String host, String username, String password, int port) {
        try {
            mFTPClient = new FTPClient();
            Log.d(TAG,"ftpConnect() connecting to the ftp server " + host + ":" + port);
            mFTPClient.connect(host, port);

            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                Log.d(TAG,"login to the ftp server");
                boolean status = mFTPClient.login(username, password);
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();
                return status;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"Error: could not connect to host " + host);
        }
        return false;
    }

    public boolean ftpDisconnect() {
        if (mFTPClient == null) {
            return true;
        }

        try {
            mFTPClient.logout();
            mFTPClient.disconnect();
            mFTPClient = null;
            return true;
        } catch (Exception e) {
            Log.d(TAG,"Error occurred while disconnecting from ftp server.");
        }
        return false;
    }

    public boolean ftpUpload(String srcFilePath, String desFileName, String desDirectory) {
        boolean status = false;
        try {
            ftpChangeDir(desDirectory);
            FileInputStream srcFileStream = new FileInputStream(srcFilePath);
            status = mFTPClient.storeFile(desFileName, srcFileStream);
            srcFileStream.close();
            return status;
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"upload failed: " + e.getLocalizedMessage());
        }
        return status;
    }

    public boolean ftpChangeDir(String path) {
        boolean status = false;
        try {
            status = mFTPClient.changeWorkingDirectory(path);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,"change directory failed: " + e.getLocalizedMessage());
        }
        return status;
    }

	public void generateUploadFile(){
		String getSN = SystemProperties.get("persist.sys.xxxx");
		Log.d(TAG,"getSN =" + getSN);
		String getIccid = SystemProperties.get("persist.sys.xxxx");
		String getImsi = SystemProperties.get("persist.sys.xxx");
		mFileName = getSN + "_" + getIccid + "_" + getImsi;
		mNeedUploadFile = mContext.getFilesDir().getAbsolutePath()+ "/" + mFileName;
		Log.d(TAG,"mNeedUploadFile =" + mNeedUploadFile+"mContext.getFilesDir().getAbsolutePath() == "+mContext.getFilesDir().getAbsolutePath());
	}
	
	private void saveFileToLocal() {
		//File file = new File("/data", mFileName);
		FileOutputStream outputStream;
		generateUploadFile();
		try {
		  outputStream = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
		  outputStream.write(mFileName.getBytes());
		  outputStream.close();
		} catch (Exception e) {
		  e.printStackTrace();
		}
    }

    public void onStartUpload( )
    {
		new Thread(new Runnable() {
			@Override
			public void run() {
				boolean connectResult = ftpConnect(FTP_SERVER, FTP_USERNAME, FTP_PASSWORD, FTP_PORT);
				if (connectResult) {
					boolean changeDirResult = ftpChangeDir(FTP_DIR);
					if (changeDirResult) {
						try {
							mFTPClient.makeDirectory(FTP_DIR);
						} catch (IOException e) {
							e.printStackTrace();
						}
						boolean uploadResult = false;
						//if(isFileExist(mNeedUploadFile)){
							saveFileToLocal();
							uploadResult = ftpUpload(mNeedUploadFile, mFileName, FTP_DIR);
						//}
						if (uploadResult) {
							Log.d(TAG,"Upload file success");
							boolean disConnectResult = ftpDisconnect();
							if(disConnectResult) {
								Log.d(TAG,"Close FTP Connect success");
							} else {
								Log.d(TAG,"Close FTP Connect falied");
							}
						} else {
							Log.d(TAG,"Upload file failed");
						}
					} else {
						Log.d(TAG,"Change FTP Directory failed");
					}

				} else {
					Log.d(TAG,"Connect FTP Server failed");
				}
            }
        }).start();		
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值