Search in sources :

Example 11 with TaskStackBuilder

use of android.support.v4.app.TaskStackBuilder in project kdeconnect-android by KDE.

the class SharePlugin method onPackageReceived.

@Override
public boolean onPackageReceived(NetworkPackage np) {
    try {
        if (np.hasPayload()) {
            Log.i("SharePlugin", "hasPayload");
            int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                // TODO Request Permission for storage
                Log.i("SharePlugin", "no Permission for Storage");
                return false;
            }
            final InputStream input = np.getPayload();
            final long fileLength = np.getPayloadSize();
            final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis()));
            //We need to check for already existing files only when storing in the default path.
            //User-defined paths use the new Storage Access Framework that already handles this.
            final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context);
            final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath();
            final String filename = customDestination ? originalFilename : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename);
            String displayName = FilesHelper.getFileNameWithoutExt(filename);
            final String mimeType = FilesHelper.getMimeTypeFromFile(filename);
            if ("*/*".equals(mimeType)) {
                displayName = filename;
            }
            final DocumentFile destinationFolderDocument = ShareSettingsActivity.getDestinationDirectory(context);
            final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType, displayName);
            final OutputStream destinationOutput = context.getContentResolver().openOutputStream(destinationDocument.getUri());
            final Uri destinationUri = destinationDocument.getUri();
            final int notificationId = (int) System.currentTimeMillis();
            Resources res = context.getResources();
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(res.getString(R.string.incoming_file_title, device.getName())).setContentText(res.getString(R.string.incoming_file_text, filename)).setTicker(res.getString(R.string.incoming_file_title, device.getName())).setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true).setProgress(100, 0, true);
            final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    boolean successful = true;
                    try {
                        byte[] data = new byte[1024];
                        long progress = 0, prevProgressPercentage = 0;
                        int count;
                        while ((count = input.read(data)) >= 0) {
                            progress += count;
                            destinationOutput.write(data, 0, count);
                            if (fileLength > 0) {
                                if (progress >= fileLength)
                                    break;
                                long progressPercentage = (progress * 10 / fileLength);
                                if (progressPercentage != prevProgressPercentage) {
                                    prevProgressPercentage = progressPercentage;
                                    builder.setProgress(100, (int) progressPercentage * 10, false);
                                    NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
                                }
                            }
                        //else Log.e("SharePlugin", "Infinite loop? :D");
                        }
                        destinationOutput.flush();
                    } catch (Exception e) {
                        successful = false;
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    } finally {
                        try {
                            destinationOutput.close();
                        } catch (Exception e) {
                        }
                        try {
                            input.close();
                        } catch (Exception e) {
                        }
                    }
                    try {
                        Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath());
                        //Update the notification and allow to open the file from it
                        Resources res = context.getResources();
                        String message = successful ? res.getString(R.string.received_file_title, device.getName()) : res.getString(R.string.received_file_fail_title, device.getName());
                        builder.setContentTitle(message).setTicker(message).setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true).setProgress(100, 100, false).setOngoing(false);
                        // TODO use FileProvider for >Nougat
                        if (Build.VERSION.SDK_INT < 24) {
                            if (successful) {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(destinationUri, mimeType);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                                stackBuilder.addNextIntent(intent);
                                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                                builder.setContentText(res.getString(R.string.received_file_text, destinationDocument.getName())).setContentIntent(resultPendingIntent);
                            }
                        }
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                        if (prefs.getBoolean("share_notification_preference", true)) {
                            builder.setDefaults(Notification.DEFAULT_ALL);
                        }
                        NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());
                        if (successful) {
                            if (!customDestination && Build.VERSION.SDK_INT >= 12) {
                                Log.i("SharePlugin", "Adding to downloads");
                                DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.addCompletedDownload(destinationUri.getLastPathSegment(), device.getName(), true, mimeType, destinationUri.getPath(), fileLength, false);
                            } else {
                                //Make sure it is added to the Android Gallery anyway
                                MediaStoreHelper.indexFile(context, destinationUri);
                            }
                        }
                    } catch (Exception e) {
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    }
                }
            }).start();
        } else if (np.has("text")) {
            Log.i("SharePlugin", "hasText");
            String text = np.getString("text");
            if (Build.VERSION.SDK_INT >= 11) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(text);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            }
            Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show();
        } else if (np.has("url")) {
            String url = np.getString("url");
            Log.i("SharePlugin", "hasUrl: " + url);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (openUrlsDirectly) {
                context.startActivity(browserIntent);
            } else {
                Resources res = context.getResources();
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(browserIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                Notification noti = new NotificationCompat.Builder(context).setContentTitle(res.getString(R.string.received_url_title, device.getName())).setContentText(res.getString(R.string.received_url_text, url)).setContentIntent(resultPendingIntent).setTicker(res.getString(R.string.received_url_title, device.getName())).setSmallIcon(R.drawable.ic_notification).setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).build();
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti);
            }
        } else {
            Log.e("SharePlugin", "Error: Nothing attached!");
        }
    } catch (Exception e) {
        Log.e("SharePlugin", "Exception");
        e.printStackTrace();
    }
    return true;
}
Also used : OutputStream(java.io.OutputStream) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) Notification(android.app.Notification) NotificationCompat(android.support.v4.app.NotificationCompat) Context(android.content.Context) ClipboardManager(android.content.ClipboardManager) DocumentFile(android.support.v4.provider.DocumentFile) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) InputStream(java.io.InputStream) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Resources(android.content.res.Resources) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder)

Example 12 with TaskStackBuilder

use of android.support.v4.app.TaskStackBuilder in project kdeconnect-android by KDE.

the class ReceiveNotificationsPlugin method onPackageReceived.

@Override
public boolean onPackageReceived(final NetworkPackage np) {
    if (!np.has("ticker") || !np.has("appName") || !np.has("id")) {
        Log.e("NotificationsPlugin", "Received notification package lacks properties");
    } else {
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MaterialActivity.class);
        stackBuilder.addNextIntent(new Intent(context, MaterialActivity.class));
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        Bitmap largeIcon = null;
        if (np.hasPayload()) {
            // default icon dimensions
            int width = 64;
            int height = 64;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                width = context.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
                height = context.getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            }
            final InputStream input = np.getPayload();
            largeIcon = BitmapFactory.decodeStream(np.getPayload());
            try {
                input.close();
            } catch (Exception e) {
            }
            if (largeIcon != null) {
                //Log.i("NotificationsPlugin", "hasPayload: size=" + largeIcon.getWidth() + "/" + largeIcon.getHeight() + " opti=" + width + "/" + height);
                if (largeIcon.getWidth() > width || largeIcon.getHeight() > height) {
                    // older API levels don't scale notification icons automatically, therefore:
                    largeIcon = Bitmap.createScaledBitmap(largeIcon, width, height, false);
                }
            }
        }
        Notification noti = new NotificationCompat.Builder(context).setContentTitle(np.getString("appName")).setContentText(np.getString("ticker")).setContentIntent(resultPendingIntent).setTicker(np.getString("ticker")).setSmallIcon(R.drawable.ic_notification).setLargeIcon(largeIcon).setAutoCancel(true).setLocalOnly(// to avoid bouncing the notification back to other kdeconnect nodes
        true).setDefaults(Notification.DEFAULT_ALL).build();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationHelper.notifyCompat(notificationManager, "kdeconnectId:" + np.getString("id", "0"), np.getInt("id", 0), noti);
    }
    return true;
}
Also used : Bitmap(android.graphics.Bitmap) MaterialActivity(org.kde.kdeconnect.UserInterface.MaterialActivity) NotificationManager(android.app.NotificationManager) InputStream(java.io.InputStream) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Notification(android.app.Notification)

Example 13 with TaskStackBuilder

use of android.support.v4.app.TaskStackBuilder in project kdeconnect-android by KDE.

the class PingPlugin method onPackageReceived.

@Override
public boolean onPackageReceived(NetworkPackage np) {
    if (!np.getType().equals(PACKAGE_TYPE_PING)) {
        Log.e("PingPlugin", "Ping plugin should not receive packets other than pings!");
        return false;
    }
    //Log.e("PingPackageReceiver", "was a ping!");
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MaterialActivity.class);
    stackBuilder.addNextIntent(new Intent(context, MaterialActivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    int id;
    String message;
    if (np.has("message")) {
        message = np.getString("message");
        id = (int) System.currentTimeMillis();
    } else {
        message = "Ping!";
        //A unique id to create only one notification
        id = 42;
    }
    Notification noti = new NotificationCompat.Builder(context).setContentTitle(device.getName()).setContentText(message).setContentIntent(resultPendingIntent).setTicker(message).setSmallIcon(R.drawable.ic_notification).setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).build();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationHelper.notifyCompat(notificationManager, id, noti);
    return true;
}
Also used : MaterialActivity(org.kde.kdeconnect.UserInterface.MaterialActivity) NotificationManager(android.app.NotificationManager) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Notification(android.app.Notification)

Example 14 with TaskStackBuilder

use of android.support.v4.app.TaskStackBuilder in project Tusky by Vavassor.

the class NotificationMaker method make.

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
    if (!filterNotification(preferences, body)) {
        return;
    }
    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;
    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }
    boolean alreadyContains = false;
    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }
    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }
    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();
    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent).setDeleteIntent(deletePendingIntent).setDefaults(// So it doesn't ring twice, notify only in Target callback
    0);
    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body)).setContentText(truncateWithEllipses(bodyForType(body), 40));
        Target mTarget = new Target() {

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);
                setupPreferences(preferences, builder);
                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };
        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default).transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary), currentNotifications.length())).setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }
    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId, builder.build());
}
Also used : NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) JSONArray(org.json.JSONArray) Drawable(android.graphics.drawable.Drawable) JSONException(org.json.JSONException) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Target(com.squareup.picasso.Target) Bitmap(android.graphics.Bitmap) RoundedTransformation(com.keylesspalace.tusky.view.RoundedTransformation) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder)

Example 15 with TaskStackBuilder

use of android.support.v4.app.TaskStackBuilder in project AprilBeacon-Android-SDK by AprilBrother.

the class NotifyService method setNormalNotification.

/**
	 * Normal Notification
	 * 
	 * @return Notification
	 * @see CreateNotification
	 */
private Notification setNormalNotification(String content) {
    Bitmap remote_picture = null;
    try {
        remote_picture = BitmapFactory.decodeStream((InputStream) new URL(sample_url).getContent());
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent resultIntent = new Intent(this, ResultActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(ResultActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    return new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setLargeIcon(remote_picture).setContentIntent(resultPendingIntent).setContentTitle("Normal Notification").setContentText(content).build();
}
Also used : Bitmap(android.graphics.Bitmap) InputStream(java.io.InputStream) NotificationCompat(android.support.v4.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) URL(java.net.URL)

Aggregations

Intent (android.content.Intent)39 TaskStackBuilder (android.support.v4.app.TaskStackBuilder)38 PendingIntent (android.app.PendingIntent)34 NotificationCompat (android.support.v4.app.NotificationCompat)20 NotificationManager (android.app.NotificationManager)14 Bitmap (android.graphics.Bitmap)13 InputStream (java.io.InputStream)10 IOException (java.io.IOException)8 URL (java.net.URL)8 Notification (android.app.Notification)7 Context (android.content.Context)5 Uri (android.net.Uri)5 SharedPreferences (android.content.SharedPreferences)3 Resources (android.content.res.Resources)3 Cursor (android.database.Cursor)3 RemoteViews (android.widget.RemoteViews)3 TaskStackBuilder (android.app.TaskStackBuilder)2 ContentResolver (android.content.ContentResolver)2 Bundle (android.os.Bundle)2 NonNull (android.support.annotation.NonNull)2