Search in sources :

Example 1 with AsyncTask

use of com.noti.main.utils.AsyncTask in project NotiSender by choiman1559.

the class DataProcess method onActionRequested.

public static void onActionRequested(Map<String, String> map, Context context) {
    String Device_id = map.get("device_id");
    String Device_name = map.get("device_name");
    String actionType = map.get("request_action");
    String actionArg = map.get("action_args");
    String[] actionArgs = {};
    if (actionArg != null) {
        actionArgs = actionArg.split("\\|");
    }
    if (actionType != null) {
        switch(actionType) {
            case "Show notification with text":
                Notify.build(context).setTitle(actionArgs[0]).setContent(actionArgs[1]).setLargeIcon(R.mipmap.ic_launcher).largeCircularIcon().setSmallIcon(R.drawable.ic_broken_image).setChannelName("").setChannelId("Notification Test").enableVibration(true).setAutoCancel(true).show();
                break;
            case "Copy text to clipboard":
                ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("Shared from " + Device_name, actionArgs[0]);
                clipboard.setPrimaryClip(clip);
                break;
            case "Open link in Browser":
                String url = actionArgs[0];
                if (!url.startsWith("http://") && !url.startsWith("https://"))
                    url = "http://" + url;
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                context.startActivity(browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                break;
            case "Trigger tasker event":
                if (Device_name != null && Device_id != null) {
                    com.noti.main.receiver.TaskerPairEventKt.callTaskerEvent(Device_name, Device_id, context);
                }
                break;
            case "Run application":
                new Handler(Looper.getMainLooper()).postDelayed(() -> Toast.makeText(context, "Remote run by NotiSender\nfrom " + map.get("device_name"), Toast.LENGTH_SHORT).show(), 0);
                String Package = actionArgs[0];
                try {
                    PackageManager pm = context.getPackageManager();
                    pm.getPackageInfo(Package, PackageManager.GET_ACTIVITIES);
                    Intent intent = pm.getLaunchIntentForPackage(Package);
                    context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + Package));
                    context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case "Run command":
                final String[] finalActionArgs = actionArgs;
                new Thread(() -> {
                    try {
                        if (finalActionArgs.length > 0)
                            Runtime.getRuntime().exec(finalActionArgs);
                    } catch (RuntimeException | IOException e) {
                        e.printStackTrace();
                    }
                }).start();
                break;
            case "Share file":
                int notificationId = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
                String notificationChannel = "DownloadFile";
                NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel(notificationChannel, "Download File Notification", NotificationManager.IMPORTANCE_DEFAULT);
                    mNotifyManager.createNotificationChannel(channel);
                }
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, notificationChannel).setContentTitle("File Download").setContentText("File name: " + actionArg).setSmallIcon(R.drawable.ic_fluent_arrow_download_24_regular).setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(true).setGroupSummary(false).setOngoing(true).setAutoCancel(false);
                mBuilder.setProgress(0, 0, true);
                mNotifyManager.notify(notificationId, mBuilder.build());
                new Thread(() -> {
                    FirebaseStorage storage = FirebaseStorage.getInstance();
                    StorageReference storageRef = storage.getReferenceFromUrl("gs://notisender-41c1b.appspot.com");
                    StorageReference fileRef = storageRef.child(context.getSharedPreferences("com.noti.main_preferences", MODE_PRIVATE).getString("UID", "") + "/" + actionArg);
                    try {
                        if (Build.VERSION.SDK_INT < 29) {
                            File targetFile = new File(Environment.getExternalStorageDirectory(), "Download/NotiSender/" + actionArg);
                            targetFile.mkdirs();
                            if (targetFile.exists())
                                targetFile.delete();
                            targetFile.createNewFile();
                            FileDownloadTask task = fileRef.getFile(targetFile);
                            task.addOnSuccessListener(taskSnapshot -> {
                                mBuilder.setContentText(actionArg + " download completed.\nCheck download folder!").setProgress(0, 0, false).setOngoing(false);
                                mNotifyManager.notify(notificationId, mBuilder.build());
                            });
                            task.addOnFailureListener(exception -> {
                                mBuilder.setContentText(actionArg + " download failed").setProgress(0, 0, false).setOngoing(false);
                                mNotifyManager.notify(notificationId, mBuilder.build());
                            });
                            task.addOnProgressListener(snapshot -> {
                                double progress = (100.0 * snapshot.getBytesTransferred()) / snapshot.getTotalByteCount();
                                mBuilder.setProgress(100, (int) progress, false);
                                mNotifyManager.notify(notificationId, mBuilder.build());
                            });
                        } else {
                            fileRef.getMetadata().addOnSuccessListener(storageMetadata -> {
                                ContentResolver resolver = context.getContentResolver();
                                ContentValues contentValues = new ContentValues();
                                contentValues.put(MediaStore.Downloads.DISPLAY_NAME, actionArg);
                                contentValues.put(MediaStore.Downloads.RELATIVE_PATH, "Download/" + "NotiSender");
                                contentValues.put(MediaStore.Downloads.MIME_TYPE, storageMetadata.getContentType());
                                contentValues.put(MediaStore.Downloads.IS_PENDING, true);
                                Uri uri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
                                Uri itemUri = resolver.insert(uri, contentValues);
                                fileRef.getStream().addOnSuccessListener(stream -> {
                                    if (itemUri != null) {
                                        AsyncTask<Void, Void, Void> downloadTask = new AsyncTask<>() {

                                            @Override
                                            protected Void doInBackground(Void... voids) {
                                                try {
                                                    InputStream inputStream = stream.getStream();
                                                    OutputStream outputStream = resolver.openOutputStream(itemUri);
                                                    byte[] buffer = new byte[102400];
                                                    int len;
                                                    while ((len = inputStream.read(buffer)) > 0) {
                                                        outputStream.write(buffer, 0, len);
                                                    }
                                                    outputStream.close();
                                                    contentValues.put(MediaStore.Images.Media.IS_PENDING, false);
                                                    resolver.update(itemUri, contentValues, null, null);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                return null;
                                            }

                                            @Override
                                            protected void onPostExecute(Void unused) {
                                                super.onPostExecute(unused);
                                                mBuilder.setContentText(actionArg + " download completed.\nCheck download folder!").setProgress(0, 0, false).setOngoing(false);
                                                mNotifyManager.notify(notificationId, mBuilder.build());
                                            }
                                        };
                                        downloadTask.execute();
                                    }
                                }).addOnFailureListener(e -> {
                                    e.printStackTrace();
                                    mBuilder.setContentText(actionArg + " download failed").setProgress(0, 0, false).setOngoing(false);
                                    mNotifyManager.notify(notificationId, mBuilder.build());
                                });
                            }).addOnFailureListener(e -> {
                                e.printStackTrace();
                                mBuilder.setContentText(actionArg + " download failed").setProgress(0, 0, false).setOngoing(false);
                                mNotifyManager.notify(notificationId, mBuilder.build());
                            });
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        mNotifyManager.cancel(notificationId);
                    }
                }).start();
                break;
        }
    }
}
Also used : Context(android.content.Context) BatteryManager(android.os.BatteryManager) PackageManager(android.content.pm.PackageManager) NotificationCompat(androidx.core.app.NotificationCompat) Environment(android.os.Environment) Date(java.util.Date) Uri(android.net.Uri) Intent(android.content.Intent) NotiListenerService.sendNotification(com.noti.main.service.NotiListenerService.sendNotification) ClipData(android.content.ClipData) PowerManager(android.os.PowerManager) FileDownloadTask(com.google.firebase.storage.FileDownloadTask) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Calendar(java.util.Calendar) ContentResolver(android.content.ContentResolver) MODE_PRIVATE(android.content.Context.MODE_PRIVATE) Handler(android.os.Handler) Looper(android.os.Looper) MediaStore(android.provider.MediaStore) Toast(android.widget.Toast) Map(java.util.Map) NotificationChannel(android.app.NotificationChannel) ClipboardManager(android.content.ClipboardManager) Notify(com.application.isradeleon.notify.Notify) Build(android.os.Build) Log(android.util.Log) FirebaseStorage(com.google.firebase.storage.FirebaseStorage) OutputStream(java.io.OutputStream) NotificationManager(android.app.NotificationManager) IntentFilter(android.content.IntentFilter) IOException(java.io.IOException) File(java.io.File) R(com.noti.main.R) StorageReference(com.google.firebase.storage.StorageReference) ContentValues(android.content.ContentValues) AsyncTask(com.noti.main.utils.AsyncTask) NotiListenerService.getUniqueID(com.noti.main.service.NotiListenerService.getUniqueID) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) PackageManager(android.content.pm.PackageManager) FirebaseStorage(com.google.firebase.storage.FirebaseStorage) NotificationCompat(androidx.core.app.NotificationCompat) ClipboardManager(android.content.ClipboardManager) ContentValues(android.content.ContentValues) FileDownloadTask(com.google.firebase.storage.FileDownloadTask) NotificationManager(android.app.NotificationManager) StorageReference(com.google.firebase.storage.StorageReference) InputStream(java.io.InputStream) AsyncTask(com.noti.main.utils.AsyncTask) Handler(android.os.Handler) Intent(android.content.Intent) IOException(java.io.IOException) JSONException(org.json.JSONException) IOException(java.io.IOException) Date(java.util.Date) NotificationChannel(android.app.NotificationChannel) ClipData(android.content.ClipData) File(java.io.File)

Aggregations

NotificationChannel (android.app.NotificationChannel)1 NotificationManager (android.app.NotificationManager)1 ClipData (android.content.ClipData)1 ClipboardManager (android.content.ClipboardManager)1 ContentResolver (android.content.ContentResolver)1 ContentValues (android.content.ContentValues)1 Context (android.content.Context)1 MODE_PRIVATE (android.content.Context.MODE_PRIVATE)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 PackageManager (android.content.pm.PackageManager)1 Uri (android.net.Uri)1 BatteryManager (android.os.BatteryManager)1 Build (android.os.Build)1 Environment (android.os.Environment)1 Handler (android.os.Handler)1 Looper (android.os.Looper)1 PowerManager (android.os.PowerManager)1 MediaStore (android.provider.MediaStore)1 Log (android.util.Log)1