gpt4 book ai didi

java - 无法使用 FileObserver 观察文件夹内的文件

转载 作者:行者123 更新时间:2023-12-01 16:47:56 27 4
gpt4 key购买 nike

我想在服务中使用 FileObserver 观察是否在 /storage/emulated/0/DCIM/Camera 中添加了任何文件/文件夹,但它不起作用。如果我的代码有什么问题请告诉我🙏。这是源代码:

AndroidManifest.xml

我添加了 uses-permissionservice 标签:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dtautosender">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<service android:name=".LogWatcherService"/>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

LogWatcherService.java

我在服务中添加了FileObserver,并重写了它的onEvent方法:

package com.example.dtautosender;

import android.app.Service;
import android.content.Intent;
import android.os.FileObserver;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.File;

public class LogWatcherService extends Service {
private static final String TAG = "LogWatcherService";
public static FileObserver fo;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final File directoryToWatch = new File(android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/");

fo = new FileObserver(directoryToWatch.getAbsolutePath(), FileObserver.ALL_EVENTS) {
@Override
public void onEvent(int event, @Nullable String path) {
Log.d(TAG, "onEvent: " + path);
}
};
fo.startWatching();

Toast.makeText(this, "Log Watcher Service is started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStartCommand: Log Watcher Service is started and trying to watch: " + directoryToWatch);

return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Log Watcher Service is stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy: Log Watcher Service is stopped");

fo.stopWatching();
}
}

MainActivity.java

在授予存储权限后打开应用程序时,我会启动该服务:

package com.example.dtautosender;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;

private static final String TAG = "MainActivity";
private boolean watcherIsEnabled = false;
private Context ctx;

private Button toggleWatcherButton;
private TextView statusTextView;

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

ctx = this;

statusTextView = findViewById(R.id.status_text);
toggleWatcherButton = findViewById(R.id.watcher_toggle);

addEventListeners();
requestPermissions();
}

private void addEventListeners() {
toggleWatcherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startLogWatcherService();
}
});
}

private void requestPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Log.d(TAG, "requestPermissions: Permission isn't granted");
} else {
ActivityCompat.requestPermissions(
this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
} else {
Log.d(TAG, "startLogWatcherService: Permission has already been granted");
startLogWatcherService();
}
}

private void startLogWatcherService() {
if (!watcherIsEnabled) {
startService(new Intent(ctx, LogWatcherService.class));
statusTextView.setText("Status: Active");
statusTextView.setTextColor(Color.parseColor("#00FF00"));
toggleWatcherButton.setText("Stop Service");
} else {
stopService(new Intent(ctx, LogWatcherService.class));
statusTextView.setText("Status: Non-Active");
statusTextView.setTextColor(Color.parseColor("#FF0000"));
toggleWatcherButton.setText("Start Service");
}
watcherIsEnabled = !watcherIsEnabled;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLogWatcherService();
} else {
toggleWatcherButton.setText("Watch file permission isn't granted by the user");
toggleWatcherButton.setEnabled(false);
}
return;
}
}
}
}

我启动了应用程序,日志上有 onStartCommand。但当发生变化时,永远不会调用 onEvent 方法。

最佳答案

这个问题我自己解决了。我认为问题是因为我的 Android Studio API 级别是 30,其中“Environment.getExternalStorageDirectory()”已被弃用。因此,为了解决这个问题,我将以下属性添加到 AndroidManifest.xml 中的应用程序标记

android:requestLegacyExternalStorage="true"

现在,我的 FileObserver 正在按预期工作

关于java - 无法使用 FileObserver 观察文件夹内的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61742222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com