Код: Выделить всё
public class MyService extends Service {
public MyService() {
}
public static FileObserver observer;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String pathToWatch = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/";
File file = new File(pathToWatch);
Log.i("MyService", "My Service Started and trying to watch " + pathToWatch);
observer = new FileObserver(file,FileObserver.ALL_EVENTS) {
@Override
public void onEvent(int event, String file) {
Log.i("MyService", "File created");
}
};
observer.startWatching();
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
Код: Выделить всё
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
},
1);
} else {
Intent intent = new Intent(this, MyService.class);
this.startService(intent);
}
}
Код: Выделить всё
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<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"
tools:ignore="GoogleAppIndexingWarning">
<service
android:name=".MyService"
android:enabled="true"
android:exported="false" />
<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>