简体   繁体   English

Android Studio 如何从WallpaperManager 获取Intent 到Service

[英]Android Studio how to get Intent into Service from WallpaperManager

I initialized a WallpaperService to use it with the WallpaperManager.我初始化了一个WallpaperService 以将它与WallpaperManager 一起使用。

My Code looks like this right now:我的代码现在看起来像这样:

 Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, WallpaperService.class));
            startActivity(intent);

My question is, how can I add a color into the Intent and use it in the WallpaperService?我的问题是,如何在 Intent 中添加颜色并在 WallpaperService 中使用它? The first idea i got was to add我的第一个想法是添加

            intent.putExtra("backGroundColor", mDefaultColor);

But this value isn't reachable in the WallpaperService.但是在WallpaperService 中无法访问此值。

The current Service looks like this:当前的服务如下所示:

public class GameOfLifeWallpaperService extends WallpaperService {

    @Override
    public Engine onCreateEngine() {
        return new GameOfLifeWallpaperEngine();
    }

    private class GameOfLifeWallpaperEngine extends Engine {
        int backgroundColor;
        ...
    }
}

In order to get the intent and it's extras/bundle, you need to Override the onStartCommand method inside the service.为了获得意图及其附加/捆绑,您需要覆盖服务内的onStartCommand方法。

There you will have access to the intent and should use a bundle to get the extras.在那里您将可以访问意图,并且应该使用捆绑包来获取额外内容。

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        Bundle bundle = intent.getExtras();
        int color = (int) bundle.get("backGroundColor");

        return START_REDELIVER_INTENT;

Notice that the method should return one of the START_STICKY_COMPATIBILITY, START_STICKY, START_NOT_STICKY, or START_REDELIVER_INTENT values.请注意,该方法应返回 START_STICKY_COMPATIBILITY、START_STICKY、START_NOT_STICKY 或 START_REDELIVER_INTENT 值之一。

Sometimes the intent data can get lost due to an error.有时,意图数据可能会因错误而丢失。 If you want to redeliver the same intent data, use START_REDELIVER_INTEN.如果要重新传送相同的意图数据,请使用 START_REDELIVER_INTEN。

You can read more about it on the android.developers.com website.您可以在android.developers.com网站上阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM