快速设置切换 Android N

Quick Settings Toggle in Android N

我正尝试在 Android N 中向我的应用程序添加快速设置开关。快速磁贴会显示,但在单击时它不会执行任何操作。我可以在触摸时看到可见的反馈,所以我知道它正在识别点击,但是点击时它没有任何反应。

这是我的服务代码:

public class QuickSettingTileService extends TileService {

    public QuickSettingTileService()
    {
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startID)
    {
        //some setup code is here

        return START_STICKY;
    }

    @Override
    public void onClick()
    {
        Context context = getApplicationContext();

        Toast.makeText(context, "Quick Setting Clicked", Toast.LENGTH_SHORT).show();
        //Toggle code is here
    }
}

我的清单中的代码几乎是直接从文档中复制过来的。只做了细微的修改:

<service
    android:name=".QuickSettingTileService"
    android:label="@string/app_name"
    android:icon="@drawable/quick_toggle_off"
    android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
    <intent-filter>
        <action android:name="android.service.quicksettings.action.QS_TILE" />
    </intent-filter>
</service>

打开应用即启动服务:

Intent serviceIntent = new Intent(this, QuickSettingTileService.class);
startService(serviceIntent);

只需从您的 QuickSettingTileService 中删除这些行 class

@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startID)
{
    //some setup code is here
    return START_STICKY;
}

无需重写 TileService 上的 onBind() 或 onStartCommand()。

此外,您不需要显式启动此服务。清单中的权限和 intent-filter 将确保 Android OS 将在您的磁贴添加到通知栏时启动您的服务。