方法onHandleIntent()没有被调用。

6

经过多小时的研究,我最终咨询了官方帮助。为什么onHandleIntent()没有被调用?这里有什么问题吗?

在主活动中的onCreate()

mService = new Intent(context, xyz.class);
startService(mService);

就是这样。调用onStartCommand(),但没有调用onHandleIntent()

package com.autoalbumwallaperplus;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

public class xyz extends IntentService {
    public xyz() {
        super("bmp");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"onStartCommand works!", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Toast.makeText(this,"onHandleIntent works!", Toast.LENGTH_SHORT).show();
    }
}

这是在OnHandleIntent内部

    String imagepath = workIntent.getStringExtra("String");
    Toast.makeText(this, "it works" , Toast.LENGTH_SHORT).show();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager hi = ((WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE));
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels << 2;

    // ... First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(imagepath, options);

    // ... Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // ... Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    decodedSampleBitmap = BitmapFactory.decodeFile(imagepath, options);

    // ... Set Wallpaper
    //Context context = getApplicationContext();
    WallpaperManager wm = WallpaperManager.getInstance(this);

    try {
        wm.setBitmap(decodedSampleBitmap);
    } catch (IOException e) {
    }

你是如何调用IntentService的? - Lalit Poptani
1个回答

11

你的Intent Service可能无法启动,因为你重写了 onStartCommand() 方法,而根据Android文档所说:

"你不应该为你的IntentService重写这个方法(onStartCommand())。相反,重写 onHandleIntent(Intent) 方法,当IntentService接收到启动请求时,系统会调用该方法。"


希望这能帮到你。


是的,那个修复了问题,但现在我有一个新问题。我正在使用上面编辑1中的代码更改背景中的壁纸。当从主Activity线程调用时,壁纸会按预期更改,但当在onHandleIntent方法内部使用时,壁纸会更改为随机的纯色。 - KickAss
如果IntentService将您的壁纸更改为某些随机纯色,则问题可能出在位图上。调试并检查它是否生成正确的位图。 - M.J
嗨,我为了保持清洁度,为这个壁纸问题创建了一个新的帖子,请检查代码:) http://stackoverflow.com/questions/15756253/onhandleintent-wallpaper-change-not-working-correctly - KickAss
当他的onStartCommand()方法实际上只是调用了super.onStartCommand()时,那么这怎么能解决问题呢?或者Toast消息是否在某种程度上导致了问题? - ban-geoengineering

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接