我正在开发一个 android 应用程序,它可以从后台将特定文件夹的图像一张一张地上传到服务器,而不会中断 UI。我实现的是来自启动器活动的 intentService 调用,具有读取 READ_EXTERNAL_STORAGE 的运行时权限。我需要上传文件夹中的所有文件,还需要上传创建或移动到文件夹中的新文件。为此,我创建了一个文件观察器类,我认为它不能正常工作。
public class DirectoryFileObserver extends FileObserver {
String aboslutePath = "";
public DirectoryFileObserver(String path) {
super(path, FileObserver.ALL_EVENTS);
aboslutePath = path;
Log.i("watch path", path);
}
@Override
public void onEvent(int event, String path) {
Log.i("FileObserver++", "File Created:" + path);
File file = new File(aboslutePath + "/" + path);
List<Skeem> mSkeemList = Skeem.find(Skeem.class, "file = ?", new String[]{file.getAbsolutePath()});
if (mSkeemList.size() == 0) {
Skeem mSkeem = new Skeem();
mSkeem.setUsername(AppConstants.UserEmail);
mSkeem.setFolderName(aboslutePath);
mSkeem.setFile(file.getAbsolutePath());
uploadService uploadService = new uploadService();
uploadService.upload(mSkeem);
}
switch (event) {
case FileObserver.ALL_EVENTS:
Log.d("All", "Path" + path);
break;
case FileObserver.CREATE:
Log.d("Create", "Path" + path);
break;
}
}
}
还创建了如下广播接收器,以在保留网络连接时恢复文件上传
public class InternetConnector_Receiver extends BroadcastReceiver {
public InternetConnector_Receiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = BaseApplication
.isActivityVisible();// Check if
// activity
// is
// visible
// or not
Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
// Check internet connection and accrding to state change the
// text of activity by calling method
if (networkInfo != null && networkInfo.isConnected()) {
Intent serviceIntent = new Intent(context, uploadService.class);
context.startService(serviceIntent);
} else {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
并在清单中
<receiver
android:name=".InternetConnector_Receiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
我将所有文件添加到状态为 false 的数据库中。
File[] files = directory.listFiles();
for (int n = 0; n < skeemList.size(); n++) {
Skeem skeem = skeemList.get(n);
for (int o = 0; o < files.length; o++) {
if (!(skeem.getFile().equalsIgnoreCase(files[o].getAbsolutePath()))) {
if (!files[o].isDirectory()) {
Skeem mSkeem = new Skeem();
mSkeem.setFile(files[o].getAbsolutePath());
mSkeem.setFolderName(directory.getName());
mSkeem.setUsername(email);
upload(mSkeem);
}
}
}
}
然后我开始上传状态为假的文件并更新状态为真的表。当我启动应用程序时,图像上传成功开始。但一段时间后它停止了。我是否使用正确的服务从后台上传文件?有没有办法上传文件夹的内容?我浏览了很多网站和链接。但我找不到我需要的确切解决方案。请帮我。