使用毕加索在通知中显示位图图像时,我收到“无法创建带有消息“未实现”的图像解码器”错误

时间:2019-06-27 10:41:41

标签: android picasso android-9.0-pie

我正在使用毕加索获取位图,以使用Firebase显示大图片样式通知。图片链接是“ https://images.pexels.com/photos/274886/pexels-photo-274886.jpeg”,我用于测试目的。毕加索无法在Android 9中创建图像解码器。

我尝试通过以下代码使用位图解码器

  private 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;
        }
    }

但是有同样的错误  V / FA:处理排队的服务任务:2 D / skia:-无法通过消息“未实现”创建图像解码器

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    Bitmap bits;
    Target target = new Target() {


        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Intent intent = new Intent(getApplicationContext(), HomeActvity.class);
            sendBigNotification(Config.title, Config.message, bitmap, intent);
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            getImage(remoteMessage);

            if (true) {

                scheduleJob();
            } else {

                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

    }


    private void getImage(final RemoteMessage remoteMessage) {
        Config.message = remoteMessage.getData().get("message");
        Config.title = remoteMessage.getData().get("title");
        Config.image = remoteMessage.getData().get("image");
        Log.i(TAG, remoteMessage.getNotification().getBody());
        Intent intent = new Intent(getApplicationContext(), HomeActvity.class);
        if (remoteMessage.getData().get("image").isEmpty()) {
            //displaying small notification
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"), intent);
        } else {


            if (remoteMessage.getData() != null) {
                Handler uiHandler = new Handler(Looper.getMainLooper());
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Picasso.get()
                                .load(remoteMessage.getData().get("image"))
                                .into(target);
                    }
                });
            }


        }
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        sendRegistrationToServer(token);
    }

    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendRegistrationToServer(String token) {

    }

    private void sendNotification(String title, String messageBody, Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setTicker(title).setWhen(0)
                        .setSmallIcon(R.drawable.ic_stat_name)
                        .setBadgeIconType(R.drawable.ic_stat_name)
                        .setColor(getApplicationContext().getResources().getColor(R.color.backgroundColor))
                        .setContentTitle(Config.title)
                        .setAutoCancel(true)
                        .setContentText(messageBody)
                        .setSound(defaultSound)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }



    private void sendBigNotification(String title, String messageBody, Bitmap imageUrl, Intent intent) {

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        style.setSummaryText(Config.message);
        style.bigPicture(imageUrl);

        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setTicker(title).setWhen(0)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setColor(getResources().getColor(R.color.backgroundColor))
                .setBadgeIconType(R.drawable.ic_stat_name)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentTitle(Config.title)
                .setAutoCancel(true)
                .setContentText(messageBody)
                .setStyle(style)
                .setSound(defaultSound)
                .setContentIntent(pendingIntent);

        // Since android Oreo notification channel is needed.
        String channelId = getString(R.string.default_notification_channel_id);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }
        manager.notify(1 /* ID of notification */, notificationBuilder.build());
    }

    private 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;
        }
    }
    }

我的Gradle文件是

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {

    compileSdkVersion 28
    def versionPropsFile = file('version.properties')
    def versionBuild
    def versionNumber

    /*Setting default value for versionBuild which is the last incremented value stored in the file */
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))
        versionBuild = versionProps['VERSION_BUILD'].toInteger()
        versionNumber = versionProps['VERSION_NUMBER'].toInteger()
    } else {
        throw new FileNotFoundException("Could not read version.properties!")
    }


    /*Wrapping inside a method avoids auto incrementing on every gradle task run. Now it runs only when we build apk*/
    ext.autoIncrementBuildNumber = {

        if (versionPropsFile.canRead()) {
            def Properties versionProps = new Properties()
            versionProps.load(new FileInputStream(versionPropsFile))
            versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
            versionNumber = versionProps['VERSION_NUMBER'].toInteger() + 1
            versionProps['VERSION_BUILD'] = versionBuild.toString()
            versionProps['VERSION_NUMBER'] = versionNumber.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
        } else {
            throw new FileNotFoundException("Could not read version.properties!")
        }
    }
    gradle.taskGraph.whenReady { taskGraph ->
        if (taskGraph.hasTask(assembleDebug)) {  /* when run debug task */
            autoIncrementBuildNumber()
        } else if (taskGraph.hasTask(assembleRelease)) { /* when run release task */
            autoIncrementBuildNumber()
        }
    }

    defaultConfig {
        applicationId "com.kuro.daksh.chetanbharat"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode versionNumber
        versionName "1.0.0." + versionBuild
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        maxSdkVersion 29
        proguardFiles 'proguard-rules.pro'
        setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
              multiDexEnabled = true
              versionNameSuffix = '1'
          }
      }
      compileOptions {
          sourceCompatibility = '1.8'
          targetCompatibility = '1.8'
      }
      compileOptions {
          sourceCompatibility JavaVersion.VERSION_1_8
          targetCompatibility JavaVersion.VERSION_1_8

      }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support:design:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        implementation 'com.android.support:support-v4:28.0.0'
        implementation 'android.arch.lifecycle:extensions:1.1.1'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

        implementation 'android.arch.navigation:navigation-fragment:1.0.0'


        implementation 'com.leodroidcoder:generic-adapter:1.0.0'

        implementation 'com.mikhaellopez:circularimageview:3.2.0'
        implementation 'com.github.javiersantos:MaterialStyledDialogs:2.1'
        implementation 'com.rengwuxian.materialedittext:library:2.1.4'
        implementation 'com.github.GoodieBag:Pinview:v1.3'
        implementation 'com.ryanjeffreybrooks:indefinitepagerindicator:1.0.10'

        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support:animated-vector-drawable:28.0.0'
        implementation 'com.google.firebase:firebase-iid:18.0.0'
        implementation 'com.google.firebase:firebase-core:16.0.9'
        implementation 'com.google.firebase:firebase-messaging:18.0.0'
        implementation 'com.google.firebase:firebase-invites:17.0.0'
        implementation 'com.google.firebase:firebase-auth:17.0.0'
        implementation 'com.google.firebase:firebase-config:17.0.0'
        implementation 'android.arch.work:work-runtime:1.0.1'
        implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
        implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
         implementation 'com.squareup.picasso:picasso:2.71828'
         // Youtube lib
         implementation 
        'com.github.PierfrancescoSoffritti:AndroidYouTubePlayer:7.0.1'
        // code generator for view

         // Butterknife
        implementation 'com.jakewharton:butterknife:8.8.1'
        annotationProcessor "com.jakewharton:butterknife-compiler:8.8.1"

        implementation 'com.github.chahine:pageindicator:0.2.7'
        implementation 'com.github.mancj:MaterialSearchBar:0.8.2'
        //Retrofit

        implementation 'com.squareup.retrofit2:retrofit:2.5.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
        implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
        implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
        implementation 'com.squareup.okhttp3:okhttp:3.12.0'
        implementation "com.squareup.okhttp3:okhttp-urlconnection:3.0.1"

        //multidex
        implementation 'com.android.support:multidex:1.0.3'


    }
    apply plugin: 'com.google.gms.google-services'
    apply plugin: 'io.fabric'

1 个答案:

答案 0 :(得分:0)

能否在gradle文件中将targetSdkVersion更改为29。