×
Namespaces

Variants
Actions

Nokia为Windows Phone提供的TweetTalk应用程序

From Nokia Developer Wiki
Jump to: navigation, search
WP Metro Icon Web.png
SignpostIcon XAML 40.png
SignpostIcon WP7 70px.png
Article Metadata

代码示例
兼容于
文章
WS_YiLunLuo 在 02 Feb 2012 创建
最后由 hamishwillee 在 19 Jul 2013 编辑

这篇文章解释了如何利用Twitter API并从Windows Phone 7应用程序中获取twitter消息以及其它信息。

Contents

简介

本文介绍如何在Windows Phone应用程序上使用Twitter API,我们会创建一个Nokia TweetTalk的应用程序,其中包括所有的Nokia Twitter账户以及有关服务,如Nokia Twitter,Nokia Developer Twitter,以及Nokia Care Twitter等账户。它也可以添加"Champions",来从Champions和世界各地的Nokia专家那里获得信息。

Windows Phone 7 SDK

为了给Windows Phone 7设备创建一个应用程序,你需要安装一个Windows Phone 7.1 SDK。你可以从这里为Windows Phone下载一个最新的SDK。

如何在Windows Phone上使用Twitter API

为了使用Twitter客户端,我们需要利用Twitter API来从Twitter账户获得各种各样的信息和消息。这个是Twitter API网站,包含各种各样的API。(https://dev.twitter.com/docs/api) . 这里就有一篇来自asp.net网络日志的文章,这篇文章写的很好,它展示了如何创建简单的windows phone 7 twitter应用程序来查询Twitter账户。它同时也展示了如何为Windows phone创建Hello world应用程序。 http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx

关于NOKIA TweetTalk应用程序

Nokia TweetTalk应用程序包含两个部分。第一部分“Nokians”包含一系列各种各样的Nokia服务的Twitter账户,像Nokia, Nokia Developer,Nokia Store,Nokia Care等。第二部分“Champions”包含一系列Nokia champions和Nokia专家Twitter账户。这个应用程序是特别为Nokia Developers和Nokia Fans创建的,在这里他们可以获得最新的有关NOKIA和Nokia Developer的信息。

截图

通过应用程序的截图,你可以更好地了解这个应用的想法。

如何创建

在这里我们将代码分成两部分。

  1. 如何列出Twitter账户的实时信息
  2. 如何显示选定的Twitter帐户的实时tweets

如何列出Twitter账户的实时信息

首先我们需要存储从twitter API获得的信息,所以我们需要创建一个TwitterItem.cs并在这个类里写入与Twitter账户相关的一些操作,就像下面所示。

public class TwitterItems
{
public string Username { get; set; }
public string tweets { get; set; }
public string imageURL { get; set; }
public string datetime { get; set; }
 
public string name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string followers_count { get; set; }
public string url { get; set; }
public string Sincedatetime { get; set; }
}

现在我们需要列出我们想要在应用程序中包括的twitter账户。要获取Twitter信息,我们将使用各种Twitter API返回XML格式数据并使用WebClient异步下载一个Twitter feed。这里共需要三行代码: (1)声明并创建WebClient

WebClient twittername = new WebClient();

(2) 附加一个事件处理程序,然后

twittername.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twittername_DownloadStringCompleted);

(3)调用异步的DownloadStringAsync方法。

twittername.DownloadStringAsync(new Uri("https://api.twitter.com/1/users/lookup.xml?screen_name=twitteracccuntId1,Twitteraccountid2,twitteraccountid3,twitteraccountidn&include_entities=true"));

DownloadStringAsync调用中,我们将像如上所示一样用twitte的用户名来传递一个Twitter Uri。这个feed将会以XML格式返回各种用户信息就像头像、姓名、关注者等。当调用完成后,DownloadStringCompleted事件将被销毁,我们创建的事件处理程序twitter_DownloadStringCompleted将被调用。 下面是完整的源代码,一步一步地解释上面提到的内容。

private void LoadNokiaTwitterAccount()
{
WebClient twittername = new WebClient();
twittername.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twittername_DownloadStringCompleted);
twittername.DownloadStringAsync(new Uri("https://api.twitter.com/1/users/lookup.xml?screen_name=nokiabrasil,NokiaHomebase,Nokia_MX,nokia_latam,nokia_ve,nokiaarg,NokiaFrance,NokiaNL,nokia_co,NokiaBE,NokiaIndonesia,NokiaPoland,nokiacanada,NokiaASE,NokiaEastAfrica,NokiaIndia,NokiaUS,Nokia_UK,NokiaPush,thenokiablog,wrtnokia,Nseries,NokiaCareers,nokiaaccess,Nokia_Connects,NokiaInnovation,NokiaHelps,Nokia_Presse,nokconv,mydailyapp,nokiabetalabs,ideasproject,ovibynokia,OviStore,qtbynokia,Symbian,MeeGoExperts,selop,windowsphone,nokiadeveloper,nokia,&include_entities=true"));
 
progressBar1.IsIndeterminate = true;
progressBar1.Visibility = Visibility.Visible;
}
 
void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
 
XElement xmlTweets = XElement.Parse(e.Result);
 
listBox1.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new TwitterItems
{
imageURL = tweet.Element("user").Element("profile_image_url").Value,
tweets = tweet.Element("text").Value,
Username = tweet.Element("user").Element("name").Value,
datetime = Convert.ToString(tweet.Element("created_at").Value).Remove(20, 5)
};
 
progressBar1.IsIndeterminate = true;
progressBar1.Visibility = Visibility.Visible;
}

为了列出twitter账户,我们将twitter信息绑定在List box控件上,在list box控件中,我们进行了这样的设计,就如截图所示在左边我们显示twitter账户的外形图片,在右显示用户名和全名。

<ListBox Tap="ListBox_Tap" Name="listbox2" Height="460" Width="383">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding imageURL}" Height="79" Width="79" VerticalAlignment="Top" Margin="0,10,8,0" />
<StackPanel Width="330">
<TextBlock Text="{Binding Username}" Foreground="Gray" FontSize="25" />
<TextBlock Text="{Binding tweets}" Foreground="Black" TextWrapping="Wrap" FontSize="21" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Output Sceenshot

如何显示选定的Twitter帐户的实时tweets

对于List box中的{{Icode|Tap}事件,我们将会重新定义第二个页面的导航,使用NavigationService.Navigate方法来输入URI参数。为了获得在第二章页面中选中的twitter id,我们需要将选中的id存储在IsolatedStorageSettings.中。所以我们创建了AppSetting类来完成它。

using System;
using System.IO.IsolatedStorage;
using System.Diagnostics;
 
namespace NokiaTweetTalk
{
public class AppSettings
{
// Our isolated storage settings
 
IsolatedStorageSettings isolatedStore;
 
// The isolated storage key names of our settings
const string DisplayNameSettingKeyName = "DisplayNameSetting";
const string ScreenNameSettingKeyName = "ScreenNameSetting";
 
// The default value of our settings
const string DisplayNameSettingDefault = "";
const string ScreenNameSettingDefault = "";
 
/// <summary>
/// Constructor that gets the application settings.
/// </summary>
public AppSettings()
{
try
{
// Get the settings for this application.
isolatedStore = IsolatedStorageSettings.ApplicationSettings;
 
}
catch (Exception e)
{
Debug.WriteLine("Exception while using IsolatedStorageSettings: " + e.ToString());
}
}
 
/// <summary>
/// Update a setting value for our application. If the setting does not
/// exist, then add the setting.
/// </summary>
/// <param name="Key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
 
// If the key exists
if (isolatedStore.Contains(Key))
{
// If the value has changed
if (isolatedStore[Key] != value)
{
// Store the new value
isolatedStore[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
isolatedStore.Add(Key, value);
valueChanged = true;
}
 
return valueChanged;
}
 
 
/// <summary>
/// Get the current value of the setting, or if it is not found, set the
/// setting to the default setting.
/// </summary>
/// <typeparam name="valueType"></typeparam>
/// <param name="Key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public valueType GetValueOrDefault<valueType>(string Key, valueType defaultValue)
{
valueType value;
 
// If the key exists, retrieve the value.
if (isolatedStore.Contains(Key))
{
value = (valueType)isolatedStore[Key];
}
// Otherwise, use the default value.
else
{
value = defaultValue;
}
 
return value;
}
 
 
/// <summary>
/// Save the settings.
/// </summary>
public void Save()
{
isolatedStore.Save();
}
 
 
/// <summary>
/// Property to get and set a DisplayName Setting Key.
/// </summary>
public string DisplayNameSetting
{
get
{
return GetValueOrDefault<string>(DisplayNameSettingKeyName, DisplayNameSettingDefault);
}
set
{
AddOrUpdateValue(DisplayNameSettingKeyName, value);
Save();
}
}
 
/// <summary>
/// Property to get and set a ScreenName Setting Key.
/// </summary>
public string ScreenNameSetting
{
get
{
return GetValueOrDefault<string>(ScreenNameSettingKeyName, ScreenNameSettingDefault);
}
set
{
AddOrUpdateValue(ScreenNameSettingKeyName, value);
Save();
}
}
}
}

这里就是将要在Listbox运行的处理Tap事件的代码。我们将要把被选中的twitter账户的用户名和显示名存储在Listbox的Tap事件,然后转到第二个页面来列出tweets。

private void ListBoxC_Tap(object sender, GestureEventArgs e)
{
try
{
ListBoxItem lst = this.listbox3.ItemContainerGenerator.ContainerFromItem(this.listbox3.SelectedItem) as ListBoxItem;
TwitterItems aItemViewModel = this.listbox3.SelectedItem as TwitterItems;
string avc = aItemViewModel.Username;
string acc = aItemViewModel.tweets;
AppSettings settings = new AppSettings();
settings.DisplayNameSetting = avc;
settings.ScreenNameSetting = acc;
NavigationService.Navigate(new Uri("/PanoramaPage1.xaml", UriKind.Relative));
}
catch (Exception ex)
{
string err = ex.Message.ToString();
}
}

在第二个页面,首先我们需要获得选中的twitter id然后存储在AppSetting。为了从AppSetting中获得值,我们需要创建对象来从settings.DisplayNameSetting中获得 twitter 账户的姓名,并从settings.SceenNameSetting获得用户名。 从第二个页面上获得这些值,我们可以将它们用在页面标题中,并将传递给BindTweet方法来作为参数,这样就能从特定的twitter id中获得信息。

public PanoramaPage1()
{
InitializeComponent();
 
// Start the Progress bar to show loading.
 
progressBar1.IsIndeterminate = true;
progressBar1.Visibility = Visibility.Visible;
 
string DisplayName = settings.DisplayNameSetting;
string ScreenName = settings.ScreenNameSetting;
if (DisplayName.Length <= 12)
PageTitle.Header = DisplayName;
else
PageTitle.Header = ScreenName;
 
BindTweet(DisplayName, ScreenName);
 
// Stop Progress bar to show loading.
progressBar1.IsIndeterminate = false;
progressBar1.Visibility = Visibility.Collapsed;
}
 
// Fetch the tweets and bind it to Listbox
private void BindTweet(string DisplayName, string ScreenName)
{
//progressBar1.IsIndeterminate = true;
//progressBar1.Visibility = Visibility.Visible;
 
WebClient twitter = new WebClient();
 
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + ScreenName + "&count=80"));
 
WebClient twitterInfo = new WebClient();
 
twitterInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitterInfo_DownloadStringCompleted);
twitterInfo.DownloadStringAsync(new Uri("https://api.twitter.com/1/users/show.xml?screen_name=" + ScreenName + "&include_entities=true"));
 
}
 
void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
 
XElement xmlTweets = XElement.Parse(e.Result);
 
listbox2.ItemsSource = from tweet in xmlTweets.Descendants("status")
select new TwitterItems
{
imageURL = tweet.Element("user").Element("profile_image_url").Value,
tweets = tweet.Element("text").Value,
Username = tweet.Element("user").Element("name").Value,
datetime = Convert.ToString(tweet.Element("created_at").Value).Remove(20, 5)
};
}

为了显示被选中的twitter id的信息,我们需要使用Twitter的一个API功能,来显示twitter账户的唯一信息。 https://api.twitter.com/1/users/show.xml?screen_name=name1

void twitterInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
 
XDocument xmlTweets = XDocument.Parse(e.Result);
XElement xmlChildT = xmlTweets.Root;
 
List<TwitterItems> lst = new List<TwitterItems>();
 
TwitterItems items = new TwitterItems();
items.imageURL = xmlChildT.Element("profile_image_url").Value;
items.name = xmlChildT.Element("name").Value;
items.Username = "@" + xmlChildT.Element("screen_name").Value;
if(xmlChildT.Element("location").Value != "")
items.location = "Location: " + xmlChildT.Element("location").Value;
items.url = xmlChildT.Element("url").Value;
items.followers_count = "Followers Count: " + xmlChildT.Element("followers_count").Value;
items.Sincedatetime = "Joining Date: " + Convert.ToString(xmlChildT.Element("created_at").Value).Remove(20, 5);
 
if (xmlChildT.Element("description").Value != "")
items.description = "Description: " + xmlChildT.Element("description").Value;
 
lst.Add(items);
lstInfo.ItemsSource = lst;
}

Output Sceenshot

安装文件

如果你的手机已解锁,你可以在你的手机上安装.xap文件。按照MSDN文章中的步骤的来注册你的手机。链接如下: How to: Register Your Phone for Development

你可以在下面的链接中获得Nokia TweetTalk应用程序的安装文件, Media:NokiaTweetTalk.zip

源代码- Nokia项目

此应用程序的源代码部署在诺基亚开发项目中。你可以从下面的链接获得诺基亚开发项目的源代码。 Link. Coming Soon.

名人TweetTalk- 商业版程序

Nokia TweetTalk有一个商业版:名人TweetTalk,现在可以在Windows Phone Marketplace下载,链接如下: Windows Phone Marketplace

This page was last modified on 19 July 2013, at 08:17.
137 page views in the last 30 days.
×