我正在尝试在服务内部注册FileObserver,以监视新照片何时保存到“ / DCIM / Camera /”。 到目前为止,我已经尝试了所有可以在网上找到的内容。我认为它应该已经可以工作了……
我确实请求清单中的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<service android:name=".FileWatcherService"
android:enabled="true"
android:exported="false"/>
<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".StartupReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
我的观察者:
public class FileWatcherService extends Service {
static String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/";
private static String TAG = "FileWatcher";
public static FileObserver fileObserver = new FileObserver(PATH, CREATE) {
@Override
public void onEvent(int i, @Nullable String s) {
Log.d(TAG, "eventttttt"); //never triggered
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: service destroyed");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: service created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
fileObserver.startWatching();
Log.d(TAG,"Service started!");
return Service.START_STICKY;
}
public static void start(Context ctx) {
Intent i = new Intent(ctx, FileWatcherService.class);
ctx.startService(i);
}
}
主要活动:
public class MainActivity extends AppCompatActivity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(".","Permission: "+permissions[0]+ "was "+grantResults[0]);
FileWatcherService.start(getApplicationContext());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
我想念什么?服务开始就很好。
感谢您的帮助。
答案 0 :(得分:0)
要在本地确认更改,请转到“设置”->“应用程序信息”->“您的应用程序”->“权限”,然后启用“存储”权限。 完全关闭您的应用程序(也从任务中删除),然后检查您的代码是否有效。
实际上似乎缺少的是请求用户访问外部存储。
参考:https://developer.android.com/training/permissions/requesting