package us.spotco.malwarescanner; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.Environment; import android.os.FileObserver; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class MalwareScannerService extends Service { private ArrayList malwareMonitors = new ArrayList<>(); @Override public final IBinder onBind(Intent intent) { return null; } @Override public final int onStartCommand(Intent intent, int flags, int startId) { malwareMonitors.clear(); addMalwareMonitor(Environment.getExternalStorageDirectory().toString()); for (RecursiveFileObserver malwareMonitor : malwareMonitors) { malwareMonitor.startWatching(); } //Toast.makeText(this, "Theia: Realtime Scanning Started", Toast.LENGTH_SHORT).show(); setForeground(); return START_STICKY; } private final void addMalwareMonitor(String monitorPath) { malwareMonitors.add(new RecursiveFileObserver(monitorPath) { @Override public void onEvent(int event, String path) { switch (event) { case FileObserver.MOVED_TO: case FileObserver.CLOSE_WRITE: File file = new File(path); if (file.exists() && file.length() > 0 && file.length() <= Utils.MAX_SCAN_SIZE_REALTIME) { Set filesToScan = new HashSet<>(); filesToScan.add(file); new MalwareScanner(null, getApplicationContext(), false).execute(filesToScan); } break; } } }); } @Override public final void onDestroy() { for (RecursiveFileObserver malwareMonitor : malwareMonitors) { malwareMonitor.stopWatching(); } malwareMonitors.clear(); System.gc(); //Toast.makeText(this, "Theia: Realtime Scanning Stopped", Toast.LENGTH_SHORT).show(); } private void setForeground() { Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getText(R.string.lblNotificationRealtimeTitle)) .setContentText(getText(R.string.lblNotificationRealtimeText)) .setPriority(Notification.PRIORITY_MIN) .setShowWhen(false) .build(); startForeground(-1, notification); } }