【问题标题】:How to set Notification icon from Imageview如何从 Imageview 设置通知图标
【发布时间】:2015-02-15 11:38:46
【问题描述】:

大家好,我正在尝试在我的应用程序中实现通知。问题是,如果可能的话,我希望每个通知都有从 imageview 中获取的特定图像。

由于documentation 表示setSmallIcon() 方法只能将int resId 作为参数,我必须使用setLargeIcon() 方法。如何将来自 URL 的图像转换为位图?

已经尝试过:

Bitmap bmp = BitmapFactory.decodeFile(getIntent().getStringExtra("stockImage"));
builder.setLargeIcon(bmp); 

它给了我这个错误

02-15 11:34:34.576    1615-1615/com.kostas.stockpredictions E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: http:/www.chatapp.info/myProject/images/ALPHA.png: open failed: ENOENT (No such file or directory)

我使用 Ion 库将此 url 设置为 Imageview,如下所示:

iv = (ImageView)findViewById(R.id.currentStockImageViewItem);
Ion.with(iv).placeholder(R.drawable.ic_chat).error(R.drawable.ic_chat).load(i.getStringExtra("stockImage"));

编辑:

class GetBitmapUrl extends AsyncTask<String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                return myBitmap;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }



        @Override
        protected void onPostExecute(Bitmap result) {
            builder.setLargeIcon(result);
        }
    }

    public void getBitmap(){
        GetBitmapUrl task = new GetBitmapUrl();
        task.execute(getIntent().getStringExtra("stockImage"));
    }

我在这里调用这个方法:

Button notify = (Button)findViewById(R.id.buttonNotify);
                    notify.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            builder = new NotificationCompat.Builder(StockItem.this);
                            builder.setContentTitle(name);
                            builder.setContentText(getString(R.string.notifyText) + " " + new DecimalFormat("###.##").format(avg));
                            builder.setWhen(System.currentTimeMillis());
                            getBitmap();
                            //builder.setSmallIcon(R.drawable.ic_launcher_stock_custom_icon);
                            builder.setTicker(getString(R.string.notifyTicker));
                            builder.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                                    + "://" + getPackageName() + "/raw/carme"));
                            builder.setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_VIBRATE);
                            builder.setAutoCancel(true);
                            Intent intent = new Intent(StockItem.this, ListLoaderActivity.class);
                            TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(StockItem.this);

                            taskStackBuilder.addNextIntent(intent);
                            taskStackBuilder.addParentStack(ListLoaderActivity.class);

                            PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentIntent(pendingIntent);
                            NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                            manager.notify(1, builder.build());

                        }
                    });

现在通知不显示了..

是否可以使用来自 imageview 的图像的位图?

提前致谢!!!

【问题讨论】:

  • 我已经尝试了接受的答案,但它给了我一个错误:02-15 11:44:49.997 1735-1735/com.kostas.stockpredictions E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.kostas.stockpredictions, PID: 1735 android.os.NetworkOnMainThreadException
  • 如果你在主流搜索引擎中搜索NetworkOnMainThreadException,你会得到:stackoverflow.com/questions/6343166/…

标签: android bitmap android-notifications android-bitmap


【解决方案1】:

自定义通知布局

  1. 通知框架允许您定义自定义 通知布局,它定义了通知的外观 一个 RemoteViews 对象。自定义布局通知类似于 普通通知,但它们基于定义的 RemoteViews XML 布局文件。

    可用于自定义通知布局的高度取决于 通知视图。普通视图布局限制为 64 dp,并且 展开的视图布局限制为 256 dp。

    要定义自定义通知布局,首先要实例化一个 扩展 XML 布局文件的 RemoteViews 对象。然后,改为 调用setContentTitle()等方法,调用setContent()。到 在自定义通知中设置内容详细信息,使用中的方法 RemoteViews 设置视图子项的值:

    在单独的文件中为通知创建 XML 布局。你 可以使用任何你想要的文件名,但你必须使用扩展名 .xml 在您的应用中,使用 RemoteViews 方法来定义您的通知 图标和文本。将此 RemoteViews 对象放入您的 NotificationCompat.Builder 通过调用 setContent()。 避免设置 RemoteViews 对象上的背景可绘制对象,因为您的文本 颜色可能变得不可读。

更多详情请访问 http://developer.android.com/guide/topics/ui/notifiers/notifications.html

【讨论】:

    【解决方案2】:

    也可以使用此代码

    Notification notification = new Notification(R.drawable.images, getText(R.string.time),
                    System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, ActivityStart.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            notification.setLatestEventInfo(this, "The Service has started",
                   "This is a foreground service", pendingIntent);
            startForeground(3, notification);
    

    要下载图像,请在 AsyncTask 的 doInBackgroundMethod 中使用以下代码。

      public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    现在重写 Asynctask 中的 onPostExecute 方法,如下所示:

    // change the return type of doInBackGround to InputStream
    @Override
    public void onPostExecute(InputStream in){
    // let the bitmap in the activity be activityBitmap
    
     Bitmap activityBitmap = BitmapFactory.decodeStream(input);
    }
    

    一个例子是

    class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private int data = 0;
    
    public BitmapWorkerTask(ImageView imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        data = params[0];
        return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
    }
    
    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
    

    }

    【讨论】:

    • 问题是我的图片来自 url 而不是来自 drawable
    • 是的。它看起来像这样 http://www.chatapp.info/myProject/images/ALPHA.png
    • 那么您可能应该在后台线程中下载图像,然后使用其可绘制形式
    • 我无法使用 Drawable 表单
    • 好吧,我只是在 asyncTask 中完成的。但是我应该如何将异步任务的执行作为位图并在通知区域中使用它?
    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多