从Settings Activity发送WallpaperService时需要BIND_WALLPAPER权限

时间:2011-09-04 08:24:55

标签: android

我一直在尝试找到一种方法,通过“设置活动”将消息传递给我的壁纸服务。

在设置中我这样做:

Context context = getApplicationContext();

Intent i = new Intent(context, RainWallpaper.class);
i.setAction("my_action");

context.startService(i);

在我的清单中,我在服务的意图过滤部分中执行了操作

<action android:name="my_action" />

最后在WallpaperService中,我覆盖了onStartCommand()

当我运行代码并调用startService()时,我收到安全异常。

  

W / ActivityManager(2466):权限拒绝:访问服务   ComponentInfo {com.myclassname}来自pid = 2466,uid = 1000需要   android.permission.BIND_WALLPAPER

所以这似乎说我需要向BIND_WALLPAPER提供设置对话框权限。因此,当我添加该权限时,设置对话框现在崩溃并出现安全异常。

1 个答案:

答案 0 :(得分:2)

我自己也在努力解决这个问题。我发现这篇文章对这个主题最有帮助。 http://groups.google.com/group/android-developers/browse_thread/thread/37c4f36db2b0779a

编辑:只是为了完成这个问题,我最终完成了这个任务,我想以同样的方式上面的帖子意味着它(但我不能确定)。 我这样做的方法是将BroadcastReceiver定义为我的WallpaperService的内部类,如下所示(但我猜也可以是一个单独的类) -

public class MyWallpaperService extends WallpaperService
{
    private static final String ACTION_PREFIX = MyWallpaperService.class.getName()+".";

    @Override
    public Engine onCreateEngine()
    {
        return new <your engine>;
    }

    private static void sendAction(Context context, String action)
    {
            Intent intent = new Intent();
            intent.setAction(MyWallpaperService.ACTION_PREFIX + action);
            context.sendBroadcast(intent);
    }

    public class WallpaperEngine extends Engine
    {
        private Receiver receiver;
        <other_members>

        public WallpaperEngine()
        {
            receiver = new Receiver(this);
            IntentFilter intentFilter = new IntentFilter();
            for (String action: <possible_action_strings>)
            {
                intentFilter.addAction(ACTION_PREFIX + action);
            }           
            registerReceiver(receiver, intentFilter);
        }
        ...
        <rest of wallpaper engine>
        ...

        @Override
        public void onDestroy()
        {
            <close wallpaper members>
            if (receiver != null)
            {
                unregisterReceiver(receiver);
            }
            receiver = null;
            super.onDestroy();
        }
    }

    public static class Receiver extends BroadcastReceiver
    {
        private MyWallpaperService myWallpaper;

        public Receiver(MyWallpaperService myWallpaper)
        {
            this.myWallpaper = myWallpaper;
        }

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            System.out.println("MyWallpaperService got " + action);
            if (!action.startsWith(ACTION_PREFIX))
            {
                return;
            }
            String instruction = action.substring(ACTION_PREFIX.length());
            <...>
        }
    }
}