windows phone开发——锁屏背景
在 Windows Phone中,用户可以选择将应用用作锁屏界面背景图像提供程序,所以在我们学会使用照片选择器之后,我们就可以尝试着使用我们的应用来为我们的手机来设置手机锁屏背景了,当然windows phone不仅支持应用设置锁屏背景,也可以在锁屏上显示我们应用的详细信息。
附上照片选择器的使用照片选择器的使用
对MainPage做下一布局
<Image x:Name="img" VerticalAlignment="Center" HorizontalAlignment="Center" Stretch="Fill" Margin="0" />
<Button x:Name="button1" Content="启动相机拍摄任务" Grid.Row="1" Click="button1_Click"/>
<Button x:Name="button2" Content="启动照片选择器" Grid.Row="2" Click="button2_Click"/>
<Button x:Name="button3" Content="设置为锁屏壁纸" Grid.Row="3" Click="button3_Click" />
<Button x:Name="button4" Content="保存图片" Grid.Row="4" Click="button4_Click"/>
若要提供手机锁屏界面背景图像,首先您需要更新应用清单文件,以将您的应用声明为锁屏界面背景的提供程序。
<Extensions>
<Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
</Extensions>
要记住。<Extension> 元素必须置于 <Tokens> 元素之后。
打开应用清单方法打开项目的属性然后使用“带编码的XML(文本编辑器)”方式打开。
然后使用照片选择器所选定的照片,在照片选择器关闭的处理事件里添加相应代码,获取所选定的照片
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
path=Save(bmp);
选定以后,我们需要使用独立存储空间来存储现在所选定的照片,以便下一步对锁屏背景的设置
public string Save(BitmapImage bmp)
{
IsolatedStorageFile storageFile=IsolatedStorageFile.GetUserStoreForApplication();
string nameA="A.jpg";
string nameB = "B.jpg";
string name = "";
if(!storageFile.FileExists(nameA)&&!storageFile.FileExists(nameB))
{
name = nameA;
}
if(storageFile.FileExists(nameA)&&!storageFile.FileExists(nameB))
{
storageFile.DeleteFile(nameA);
name = nameB;
}
if(!storageFile.FileExists(nameA)&&storageFile.FileExists(nameB))
{
storageFile.DeleteFile(nameB);
name = nameA;
}
IsolatedStorageFileStream filestream = storageFile.CreateFile(name);
WriteableBitmap wbmp = new WriteableBitmap(bmp);
wbmp.SaveJpeg(filestream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 85);
filestream.Close();
return string.Format("ms-appdata:///local/{0}", name);
}
以上代码,还提供了一种处理当存在文件名字相同时的处理办法,并返回文件存储位置的绝对路径,有了决定路径就可以实现对锁屏背景的设置
private async void button3_Click(object sender,EventArgs e)
{
try
{
var isProvider = LockScreenManager.IsProvidedByCurrentApplication;
if (!isProvider)
{
var op = await LockScreenManager.RequestAccessAsync();
isProvider = op == LockScreenRequestResult.Granted;
}
if (isProvider)
{
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
LockScreen.SetImageUri(uri);
}
else
{
MessageBox.Show("You said no, so I can't update your background.");
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
其中RequestAccessAsync()会弹出一个对话框,来询问是否允许我们的应用作为锁屏背景。
这样我们就可以使用我们的应用作为锁屏背景了!