Hi
I'm new to this android development.
I've read a lot on the net how to do it, but I can't get the speed I want/expect.
In init:
bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
my onDraw method:
protected void onDraw(Canvas canvas) {
for (int j = 0; j < HEIGHT-2; j++) {
int heat = 0;
for (int i = 0; i < WIDTH; i++) {
heat = firebuf[j];
bitmap.setPixel(i, j, palbuf[heat]);
}
}
canvas.drawBitmap(bitmap, 0, 0, null);
// refresh the canvas
invalidate();
}
Is this the way to do it?
I come from the PC world, where I would have 2 buffers directly to the gfx card. Write in one while the other is shown and then switch.
Couldn't find out how to do it on the android.
Nobody knows how to update the sceren fast?
no idea... doesnt look like it ... most the ppl here doing roms/kernel dev... very few app developers
Okay thanks
there are android dev forums ...
and lots of info at developer.android.com
id ask arround there
Related
Questions
As mentioned in the text below the TakePicture() method is not working properly on the HTC HD 2 device. It would be nice if someone could look at the code below and tell me if it is right or wrong what I'm doing.
Introduction
I recently asked a question on another forum about displaying a video preview and taking camera image with DirectShow. The tricky thing about the topic is, that it's very hard to find good examples and the documentation and the framework itself is very hard to understand for someone who is new to windows programming and C++ in general.
Nevertheless I managed to create a class that implements most of this features and probably works with most mobile devices. Probably because as far as I know the DirectShow implementation depends a lot on the device itself. I could only test it with the HTC HD and HTC HD2, which are known as quite incompatible.
HTC HD
- Working: Video preview, writing photo to file
- Not working: Set video resolution (CRASH), set photo resolution (LOW quality)
HTC HD 2
- Working: Set video resolution, set photo resolution
- Problematic: Video Preview rotated
- Not working: Writing photo to file
To make it easier for others by providing a working example, I decided to share everything I have got so far below. I removed all of the error handling for the sake of simplicity. As far as documentation goes, I can recommend you to read the MSDN documentation about the topic. After that the code below is pretty straight forward.
Code:
void Camera::Init()
{
CreateComObjects();
_captureGraphBuilder->SetFiltergraph(_filterGraph);
InitializeVideoFilter();
InitializeStillImageFilter();
}
Dipslay a video preview (working with any tested handheld):
Code:
void Camera::DisplayVideoPreview(HWND windowHandle)
{
IVideoWindow *_vidWin;
_filterGraph->QueryInterface(IID_IMediaControl,(void **) &_mediaControl);
_filterGraph->QueryInterface(IID_IVideoWindow, (void **) &_vidWin);
_videoCaptureFilter->QueryInterface(IID_IAMVideoControl,
(void**) &_videoControl);
_captureGraphBuilder->RenderStream(&PIN_CATEGORY_PREVIEW,
&MEDIATYPE_Video, _videoCaptureFilter, NULL, NULL);
CRect rect;
long width, height;
GetClientRect(windowHandle, &rect);
_vidWin->put_Owner((OAHWND)windowHandle);
_vidWin->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);
_vidWin->get_Width(&width);
_vidWin->get_Height(&height);
height = rect.Height();
_vidWin->put_Height(height);
_vidWin->put_Width(rect.Width());
_vidWin->SetWindowPosition(0,0, rect.Width(), height);
_mediaControl->Run();
}
HTC HD2: If set SetPhotoResolution() is called FindPin will return E_FAIL. If not, it will create a file full of null bytes. HTC HD: Works
void Camera::TakePicture(WCHAR *fileName)
{
CComPtr<IFileSinkFilter> fileSink;
CComPtr<IPin> stillPin;
CComPtr<IUnknown> unknownCaptureFilter;
CComPtr<IAMVideoControl> videoControl;
_imageSinkFilter.QueryInterface(&fileSink);
fileSink->SetFileName(fileName, NULL);
_videoCaptureFilter.QueryInterface(&unknownCaptureFilter);
_captureGraphBuilder->FindPin(unknownCaptureFilter, PINDIR_OUTPUT,
&PIN_CATEGORY_STILL, &MEDIATYPE_Video, FALSE, 0, &stillPin);
_videoCaptureFilter.QueryInterface(&videoControl);
videoControl->SetMode(stillPin, VideoControlFlag_Trigger);
}
Set resolution: Works great on HTC HD2. HTC HD won't allow SetVideoResolution() and only offers one low resolution photo resolution:
Code:
void Camera::SetVideoResolution(int width, int height)
{
SetResolution(true, width, height);
}
void Camera::SetPhotoResolution(int width, int height)
{
SetResolution(false, width, height);
}
void Camera::SetResolution(bool video, int width, int height)
{
IAMStreamConfig *config;
config = NULL;
if (video)
{
_captureGraphBuilder->FindInterface(&PIN_CATEGORY_PREVIEW,
&MEDIATYPE_Video, _videoCaptureFilter, IID_IAMStreamConfig,
(void**) &config);
}
else
{
_captureGraphBuilder->FindInterface(&PIN_CATEGORY_STILL,
&MEDIATYPE_Video, _videoCaptureFilter, IID_IAMStreamConfig,
(void**) &config);
}
int resolutions, size;
VIDEO_STREAM_CONFIG_CAPS caps;
config->GetNumberOfCapabilities(&resolutions, &size);
for (int i = 0; i < resolutions; i++)
{
AM_MEDIA_TYPE *mediaType;
if (config->GetStreamCaps(i, &mediaType,
reinterpret_cast<BYTE*>(&caps)) == S_OK )
{
int maxWidth = caps.MaxOutputSize.cx;
int maxHeigth = caps.MaxOutputSize.cy;
if(maxWidth == width && maxHeigth == height)
{
VIDEOINFOHEADER *info =
reinterpret_cast<VIDEOINFOHEADER*>(mediaType->pbFormat);
info->bmiHeader.biWidth = maxWidth;
info->bmiHeader.biHeight = maxHeigth;
info->bmiHeader.biSizeImage = DIBSIZE(info->bmiHeader);
config->SetFormat(mediaType);
DeleteMediaType(mediaType);
break;
}
DeleteMediaType(mediaType);
}
}
}
Other methods used to build the filter graph and create the COM objects:
v
Code:
oid Camera::CreateComObjects()
{
CoInitialize(NULL);
CoCreateInstance(CLSID_CaptureGraphBuilder, NULL, CLSCTX_INPROC_SERVER,
IID_ICaptureGraphBuilder2, (void **) &_captureGraphBuilder);
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IGraphBuilder, (void **) &_filterGraph);
CoCreateInstance(CLSID_VideoCapture, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (void**) &_videoCaptureFilter);
CoCreateInstance(CLSID_IMGSinkFilter, NULL, CLSCTX_INPROC,
IID_IBaseFilter, (void**) &_imageSinkFilter);
}
void Camera::InitializeVideoFilter()
{
_videoCaptureFilter->QueryInterface(&_propertyBag);
wchar_t deviceName[MAX_PATH] = L"\0";
GetDeviceName(deviceName);
CComVariant comName = deviceName;
CPropertyBag propertyBag;
propertyBag.Write(L"VCapName", &comName);
_propertyBag->Load(&propertyBag, NULL);
_filterGraph->AddFilter(_videoCaptureFilter,
L"Video Capture Filter Source");
}
void Camera::InitializeStillImageFilter()
{
_filterGraph->AddFilter(_imageSinkFilter, L"Still image filter");
_captureGraphBuilder->RenderStream(&PIN_CATEGORY_STILL,
&MEDIATYPE_Video, _videoCaptureFilter, NULL, _imageSinkFilter);
}
void Camera::GetDeviceName(WCHAR *deviceName)
{
HRESULT hr = S_OK;
HANDLE handle = NULL;
DEVMGR_DEVICE_INFORMATION di;
GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E,
0x4D, 0x7E, 0x3C, 0x86 };
di.dwSize = sizeof(di);
handle = FindFirstDevice(DeviceSearchByGuid, &guidCamera, &di);
StringCchCopy(deviceName, MAX_PATH, di.szLegacyName);
}
Full header file:
Code:
#ifndef __CAMERA_H__
#define __CAMERA_H__
class Camera
{
public:
void Init();
void DisplayVideoPreview(HWND windowHandle);
void TakePicture(WCHAR *fileName);
void SetVideoResolution(int width, int height);
void SetPhotoResolution(int width, int height);
private:
CComPtr<ICaptureGraphBuilder2> _captureGraphBuilder;
CComPtr<IGraphBuilder> _filterGraph;
CComPtr<IBaseFilter> _videoCaptureFilter;
CComPtr<IPersistPropertyBag> _propertyBag;
CComPtr<IMediaControl> _mediaControl;
CComPtr<IAMVideoControl> _videoControl;
CComPtr<IBaseFilter> _imageSinkFilter;
void GetDeviceName(WCHAR *deviceName);
void InitializeVideoFilter();
void InitializeStillImageFilter();
void CreateComObjects();
void SetResolution(bool video, int width, int height);
};
#endif
Hey, in the FindInterface for the you're not checking the return code, which has to be S_OK; if not, the config is NULL and using config-> will cause your crash. If FindInterface for PIN_CATEGORY_PREVIEW is failing, try FindInterface for PIN_CATEGORY_CAPTURE.
Hi Everyone,
I'm making a windows mobile app in C# to help those affected by alzheimers disease and other dimentia related conditions
One function of the app is sending SMS text messages and so I'd really like to include the battery charge percentage in each text, but I can't find how to do so!
How can I put this in my program?
Thanks!
James
Use PowerBatteryStrength of Status.SystemProperty!
I know it's something to do with
Code:
Microsoft.WindowsMobile.Status.SystemState.PowerBatteryStrength.ToString();
but beyond that I'm lost! How do I put it in to my code so that I just get the string "Battery level: 42%" for example?
Signal strenght and battery level example
Hi,
Here is a simple example on how you can use the SystemState and SystemProperties.
Hope this will help you.
Code:
using System;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Status;
namespace SignalAndBatteryLevel
{
public partial class BatteryAndSignalLevel : Form
{
private readonly SystemState _signalStrenght =
new SystemState(SystemProperty.PhoneSignalStrength);
private readonly SystemState _batteryLevel =
new SystemState(SystemProperty.PowerBatteryStrength);
private readonly SystemState _batteryState =
new SystemState(SystemProperty.PowerBatteryState);
public BatteryAndSignalLevel()
{
InitializeComponent();
SetSignalStrenght();
SetBatteryLevel();
_signalStrenght.Changed +=
SignalStrenghtChanged;
_batteryLevel.Changed += BatteryLevelChanged;
_batteryState.Changed += BatteryLevelChanged;
}
private void SignalStrenghtChanged(object sender,
EventArgs e)
{
SetSignalStrenght();
}
public void SetSignalStrenght()
{
_lblSignalStrenght.Text =
SystemState.PhoneSignalStrength.ToString();
}
private void BatteryLevelChanged(object sender,
EventArgs e)
{
SetBatteryLevel();
}
private void SetBatteryLevel()
{
_lblBatteryLevel.Text = GetBatteryLevel();
}
private string GetBatteryLevel()
{
string batteryLevel = "Unknown";
if (SystemState.PowerBatteryState ==
BatteryState.Charging)
{
return "Charging";
}
switch (SystemState.PowerBatteryStrength)
{
case BatteryLevel.VeryLow:
batteryLevel = "Very lowt";
break;
case BatteryLevel.Low:
batteryLevel = "Low";
break;
case BatteryLevel.Medium:
batteryLevel = "Medium";
break;
case BatteryLevel.High:
batteryLevel = "High";
break;
case BatteryLevel.VeryHigh:
batteryLevel = "Very High";
break;
}
return batteryLevel;
}
}
}
Hi PerOla,
This is really a good solution and working fine for me. Its really help me out in one of my project.
Thank you very much....
Vimal Panchal
I'm currently playing with SMS Backgroud task sample(Windows 8) sample application
I'm trying to display the Received SMS message onto the form but it is being processed on another "Project properties SMSbackgroundTask" which contains no form and my main form in project properties "Smsbackgroundtasksample"
I created this in SMSbackgroundtask
Code:
setSMSBody(smsTextMessage.Body);
Under
async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)
and
Code:
public void setSMSBody(string bodyy)
{
string body;
body = bodyy;
}
All in the backgroundtask(no form)
I'm trying to read it from the form project (SMSBackgroundTasksample) but i cant read it even tho its public..
I did this because i didnt know where i can intercept the MEssage from in the main page which i believe because it havent been processed at the main SMSbackgroundtask.
The following is the codes in backgroundtask (if you know where to intercept)
Code:
(SMSbackgroundtask)
using System;
using System.Diagnostics;
using System.Threading;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.Devices.Sms;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using System.Threading.Tasks;
//
// The namespace for the background tasks.
//
namespace SmsBackgroundTask
{
//
// A background task always implements the IBackgroundTask interface.
//
public sealed class SampleSmsBackgroundTask : IBackgroundTask
{
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// Associate a cancellation handler with the background task.
//
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
ManualResetEvent manualEventWaiter = new ManualResetEvent(false);
manualEventWaiter.Reset();
//
// Do the background task activity.
//
DisplayToastAsync(taskInstance, manualEventWaiter);
//
// Wait till the async operation is done. We need to do this else the background process will exit
//
manualEventWaiter.WaitOne(5000);
Debug.WriteLine("Background " + taskInstance.Task.Name + ("process ran"));
}
async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)
{
SmsReceivedEventDetails smsDetails = (SmsReceivedEventDetails)taskInstance.TriggerDetails;
SmsDevice smsDevice = (SmsDevice)await SmsDevice.FromIdAsync(smsDetails.DeviceId);
SmsBinaryMessage smsEncodedmsg = (SmsBinaryMessage)await smsDevice.MessageStore.GetMessageAsync(smsDetails.MessageIndex);
SmsTextMessage smsTextMessage = Windows.Devices.Sms.SmsTextMessage.FromBinaryMessage(smsEncodedmsg);
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements.Item(0).AppendChild(toastXml.CreateTextNode(smsTextMessage.From));
stringElements.Item(1).AppendChild(toastXml.CreateTextNode(smsTextMessage.Body));
ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);
setSMSBody(smsTextMessage.Body);
manualEventWaiter.Set();
}
public void setSMSBody(string bodyy)
{
string body;
body = bodyy;
}
//
// Handles background task cancellation.
//
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//
// Indicate that the background task is canceled.
//
Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
}
}
}
And the following is the code behind of the form (SMSbackgroundtasksample)
Code:
using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Sms;
namespace SmsBackgroundTaskSample
{
partial class MainPage
{
private const string SampleSmsBackgroundTaskEntryPoint = "SmsBackgroundTask.SampleSmsBackgroundTask";
private const string SampleSmsBackgroundTaskName = "SampleSmsBackgroundTask";
private CoreDispatcher SampleDispatcher;
private const string OperatorNotificationTaskEntryPoint = "SmsBackgroundTask.OperatorNotification";
private const string OperatorNotificationTaskName = "OperatorNotificationTask";
public MainPage()
{
InitializeComponent();
//
// Take a reference to the main window dispatcher object to the UI.
//
SampleDispatcher = Window.Current.CoreWindow.Dispatcher;
ScenarioList.SelectionChanged += new SelectionChangedEventHandler(ScenarioList_SelectionChanged);
ScenarioList.SelectedItem = Scenario1;
//
// Associate CS event handlers with application activated, suspending, and resuming events.
//
App.Current.Resuming += OnResume;
App.Current.Suspending += OnSuspend;
try
{
//
// Initialize state-based registration of currently registered background tasks.
//
InitializeRegisteredSmsBackgroundTasks();
//
// Register a background task for the network operator notification system event.
// This event is triggered when the application is updated.
//
RegisterOperatorNotificationTask();
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}
//
// Application's suspend handler.
//
private void OnSuspend(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
//
// Persist application's storage
//
}
//
// Application's resume handler.
//
private void OnResume(object sender, object e)
{
//
// Recover application's state from storage
//
}
//
// Handler to show selected scenario.
//
void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ResetAll();
if (ScenarioList.SelectedItem == Scenario1)
{
Scenario1Input.Visibility = Visibility.Visible;
Scenario1Output.Visibility = Visibility.Visible;
}
else if (ScenarioList.SelectedItem == Scenario2)
{
Scenario2Input.Visibility = Visibility.Visible;
Scenario2Output.Visibility = Visibility.Visible;
}
}
public void ResetAll()
{
Error.Text = "";
Scenario1Input.Visibility = Visibility.Collapsed;
Scenario1Output.Visibility = Visibility.Collapsed;
Scenario2Input.Visibility = Visibility.Collapsed;
Scenario2Output.Visibility = Visibility.Collapsed;
}
//
// Updates button text in the sample application UI.
//
private void UpdateSampleSmsBackgroundTaskUIState(bool Registered)
{
if (Registered)
{
SampleSmsBackgroundTaskStatus.Text = "Registered";
RegisterSampleSmsBackgroundTaskButton.IsEnabled = false;
UnregisterSampleSmsBackgroundTaskButton.IsEnabled = true;
}
else
{
SampleSmsBackgroundTaskStatus.Text = "Unregistered";
RegisterSampleSmsBackgroundTaskButton.IsEnabled = true;
UnregisterSampleSmsBackgroundTaskButton.IsEnabled = false;
}
}
//
// Registers a background task for the operator notification system event.
// This event occurs when the application is updated.
//
private void RegisterOperatorNotificationTask()
{
//
// Check whether the operator notification background task is already registered.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == OperatorNotificationTaskName)
{
//
// The task is already registered.
//
return;
}
}
//
// The operator notification background task is not already registered.
//
//
// Prepare to create the background task.
//
//
// Get all active Mobilebroadband accounts
//
var allAccounts = Windows.Networking.NetworkOperators.MobileBroadbandAccount.AvailableNetworkAccountIds;
//
// Pick the desired account. For demonstration we pick the first one
//
if (allAccounts.Count > 0)
{
//
// Create a new background task builder.
//
// For the sake of simplicity, assume we want to use the first account
// Refer to the Mobilebroadband Account API's how to select specific account ID
var myTrigger = new Windows.ApplicationModel.Background.NetworkOperatorNotificationTrigger(allAccounts[0]);
var myTaskBuilder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
//
// Associate the trigger with the background task builder.
//
myTaskBuilder.SetTrigger(myTrigger);
//
// Specify the background task to run when the trigger fires.
//
myTaskBuilder.TaskEntryPoint = OperatorNotificationTaskEntryPoint;
//
// Name the background task.
//
myTaskBuilder.Name = OperatorNotificationTaskName;
//
// Register the background task.
//
var myTask = myTaskBuilder.Register();
//
// Associate progress and completed event handlers with the new background task.
//
myTask.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
myTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
//
// Update ui to show the task is registered.
//
OperatorNotificationStatus.Text = "Registered";
}
else
{
OperatorNotificationStatus.Text = "No Mobilebroadband accounts found";
}
}
//
// Registers a background task for a SmsReceived event.
//
private async void RegisterSmsSampleBackgroundTask(object sender, RoutedEventArgs args)
{
//
// Prepare to create the background task.
//
// SMS is a sensitive capability and the user may be prompted for consent. If the app
// does not obtain permission for the package to have access to SMS before the background
// work item is run (perhaps after the app is suspended or terminated), the background
// work item will not have access to SMS and will have no way to prompt the user for consent
// without an active window. Here, any available SMS device is activated in order to ensure
// consent. Your app will likely do something with the SMS device as part of its features.
Error.Text = "";
try
{
SmsDevice smsDevice = (SmsDevice)await SmsDevice.GetDefaultAsync();
try
{
//
// Create a new background task builder.
//
var myTaskBuilder = new BackgroundTaskBuilder();
//
// Create a new SmsReceived trigger.
//
var myTrigger = new SystemTrigger(SystemTriggerType.SmsReceived, false);
//
// Associate the SmsReceived trigger with the background task builder.
//
myTaskBuilder.SetTrigger(myTrigger);
//
// Specify the background task to run when the trigger fires.
//
myTaskBuilder.TaskEntryPoint = SampleSmsBackgroundTaskEntryPoint;
//
// Name the background task.
//
myTaskBuilder.Name = SampleSmsBackgroundTaskName;
//
// Register the background task.
//
var myTask = myTaskBuilder.Register();
//
// Associate progress and completed event handlers with the new background task.
//
myTask.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
myTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
UpdateSampleSmsBackgroundTaskUIState(true);
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}
catch (Exception ex)
{
Error.Text = "Failed to find SMS device\n" + ex.Message;
}
}
//
// Handle currently registered background tasks on application startup.
//
public void InitializeRegisteredSmsBackgroundTasks()
{
try
{
//
// Initialize UI elements based on currently registered background tasks
// and associate background task progress and completed event
// handlers with each background task.
//
UpdateSampleSmsBackgroundTaskUIState(false);
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
switch (cur.Value.Name)
{
case SampleSmsBackgroundTaskName:
UpdateSampleSmsBackgroundTaskUIState(true);
break;
}
cur.Value.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
cur.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}
//
// Handle background task completion.
//
private void OnCompletedInvokedHandler(object sender, InvokedHandlerArgs e)
{
try
{
var task = sender as IBackgroundTaskRegistration;
var args = e.Context as BackgroundTaskCompletedEventArgs;
if ((task != null) && (args != null))
{
//
// If the background task threw an exception, display the exception in
// the error text box.
//
if (args.Status != null)
{
throw args.Status;
}
//
// Update the UI with the completion status of the background task
// The Run method of the background task sets this status.
//
var key = task.TaskId.ToString();
var settings = ApplicationData.Current.LocalSettings;
switch (task.Name)
{
case SampleSmsBackgroundTaskName:
SampleSmsBackgroundTaskStatus.Text = settings.Values[key].ToString();
break;
case OperatorNotificationTaskName:
OperatorNotificationStatus.Text = settings.Values[key].ToString();
break;
}
}
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}
//
// Dispatch background task completion.
//
private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
//
// Update the UI with progress reported by the background task.
//
SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
OnCompletedInvokedHandler,
sender,
e);
}
//
// Handle background task progress.
//
private void OnProgressInvokedHandler(object sender, InvokedHandlerArgs e)
{
var task = sender as IBackgroundTaskRegistration;
var args = e.Context as BackgroundTaskProgressEventArgs;
if ((task != null) && (args != null))
{
switch (task.Name)
{
case SampleSmsBackgroundTaskName:
SampleSmsBackgroundTaskProgress.Text = "Progress: " + args.Progress + "%";
break;
case OperatorNotificationTaskName:
OperatorNotificationProgress.Text = "Progress: " + args.Progress + "%";
break;
}
}
}
//
// Dispatch background task progress.
//
private void OnProgress(IBackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs e)
{
//
// Update the UI with progress reported by the background task.
//
SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
OnProgressInvokedHandler,
sender,
e);
}
//
// Unregister background tasks with specified name.
//
private void UnregisterSmsBackgroundTasks(string name)
{
//
// Loop through all background tasks and unregister any with SampleSmsBackgroundTaskName
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == name)
{
cur.Value.Unregister(true);
}
}
}
//
// Handle the Unregister button click.
//
private void UnregisterSmsSampleBackgroundTask(object sender, RoutedEventArgs args)
{
UnregisterSmsBackgroundTasks(SampleSmsBackgroundTaskName);
UpdateSampleSmsBackgroundTaskUIState(false);
}
}
}
It would be nice if you could also teach me how to send using this library
msdn.microsoft(doT)com/en-us/library/windows/apps/br206567.aspx
Thanks. I believe it would greatly improve my skills. Hope you could help me out. Thank you
hello guys and girls,
I have a very peculiar problem with my application (two actually, working together to make a bigger problem)
I have a resume tile, which allows the users to resume working on the picture they were working after navigating away from the game.
Now, the users can choose pictures in their media lib to use in the game.
However, after i sync my phone to laptop, unplug it, then try to use the resume tile, it simply brings me to main page and does not continue doing the resume as it should do. This only happens with pictures from photochooser task: the ones integrated in the app work fine.
The photochooser task also refuses to work properly until i start the app "the usual way" and not from the resume tile. It basically goes back to the MainPage no matter what.
So, what's with all this? I think it has something to do with the syncing messing up isolated storage and phone storage.
here's some code:
MainPage:
Basically, I'm using some messages to know from where i navigated to the MainPage. The "resumeTile" message is obviously coming from the resume tile, whereas "FromPlay" means the player just left the play page.
App.IsFirstLoaded is used to known that it loaded already and should ignore the "ResumeTile" message and continue with the resume, but not to repeat the same feat in case the user navigates from any page in the game.
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string msesage = null;
try
{
NavigationContext.QueryString.TryGetValue("message", out msesage);
if (msesage == "resumeTile")
{
App.isFirstLoaded = true;
}
if (msesage == "FromPlay")
{
NavigationService.RemoveBackEntry();
}
if (App.isFirstLoaded == true)
{
resume_SubmitResume();
App.isFirstLoaded = false;
msesage = null;
}
else
{
//NavigationService.RemoveBackEntry();
base.OnNavigatedTo(e);
if (msg == "openPlay")
{
string msggs = msg;
msg = null;
if (portrait)
{
NavigationService.Navigate(new Uri("/PlayPage.xaml?msg=" + msggs, UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msggs, UriKind.Relative));
}
}
}
}
catch (NullReferenceException)
{
}
}
and here is the photochooser task completed event handler
Code:
void photochoser_Completed(object sender, PhotoResult e)
{
string path = "mhgcjtcthgg.jpg";
if (e.TaskResult == TaskResult.OK)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, IsolatedStorageFile.GetUserStoreForApplication()))
{
if (e.Error == null)
{
if (App.AutoSave == true)
{
MediaLibrary ml = new MediaLibrary();
ml.SavePicture("CountlessPuzzles" + DateTime.Now.ToShortTimeString(), e.ChosenPhoto);
}
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);
if (wb.PixelHeight <= wb.PixelWidth)
{
Extensions.SaveJpeg(wb, fs, DHeigh, DWidth, 0, 100);
//NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msg, UriKind.Relative));
}
else
{
Extensions.SaveJpeg(wb, fs, DWidth, DHeigh, 0, 100);
//NavigationService.Navigate(new Uri("PlayPage.xaml?msg=" + msg, UriKind.Relative));
portrait = true;
}
}
}
}
msg = "openPlay";
}
else
{
isDataSavedInIsolatedStorage = false;
}
// e.ChosenPhoto.Close();
}
So, any ideas?
mcosmin222 said:
hello guys and girls,
I have a very peculiar problem with my application (two actually, working together to make a bigger problem)
I have a resume tile, which allows the users to resume working on the picture they were working after navigating away from the game.
Now, the users can choose pictures in their media lib to use in the game.
However, after i sync my phone to laptop, unplug it, then try to use the resume tile, it simply brings me to main page and does not continue doing the resume as it should do. This only happens with pictures from photochooser task: the ones integrated in the app work fine.
The photochooser task also refuses to work properly until i start the app "the usual way" and not from the resume tile. It basically goes back to the MainPage no matter what.
So, what's with all this? I think it has something to do with the syncing messing up isolated storage and phone storage.
here's some code:
MainPage:
Basically, I'm using some messages to know from where i navigated to the MainPage. The "resumeTile" message is obviously coming from the resume tile, whereas "FromPlay" means the player just left the play page.
App.IsFirstLoaded is used to known that it loaded already and should ignore the "ResumeTile" message and continue with the resume, but not to repeat the same feat in case the user navigates from any page in the game.
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string msesage = null;
try
{
NavigationContext.QueryString.TryGetValue("message", out msesage);
if (msesage == "resumeTile")
{
App.isFirstLoaded = true;
}
if (msesage == "FromPlay")
{
NavigationService.RemoveBackEntry();
}
if (App.isFirstLoaded == true)
{
resume_SubmitResume();
App.isFirstLoaded = false;
msesage = null;
}
else
{
//NavigationService.RemoveBackEntry();
base.OnNavigatedTo(e);
if (msg == "openPlay")
{
string msggs = msg;
msg = null;
if (portrait)
{
NavigationService.Navigate(new Uri("/PlayPage.xaml?msg=" + msggs, UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msggs, UriKind.Relative));
}
}
}
}
catch (NullReferenceException)
{
}
}
and here is the photochooser task completed event handler
Code:
void photochoser_Completed(object sender, PhotoResult e)
{
string path = "mhgcjtcthgg.jpg";
if (e.TaskResult == TaskResult.OK)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, IsolatedStorageFile.GetUserStoreForApplication()))
{
if (e.Error == null)
{
if (App.AutoSave == true)
{
MediaLibrary ml = new MediaLibrary();
ml.SavePicture("CountlessPuzzles" + DateTime.Now.ToShortTimeString(), e.ChosenPhoto);
}
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);
if (wb.PixelHeight <= wb.PixelWidth)
{
Extensions.SaveJpeg(wb, fs, DHeigh, DWidth, 0, 100);
//NavigationService.Navigate(new Uri("/PlayPageLandscape.xaml?msg=" + msg, UriKind.Relative));
}
else
{
Extensions.SaveJpeg(wb, fs, DWidth, DHeigh, 0, 100);
//NavigationService.Navigate(new Uri("PlayPage.xaml?msg=" + msg, UriKind.Relative));
portrait = true;
}
}
}
}
msg = "openPlay";
}
else
{
isDataSavedInIsolatedStorage = false;
}
// e.ChosenPhoto.Close();
}
So, any ideas?
Click to expand...
Click to collapse
Photochooser does not work when the phone is syncing via zune, maybe once the app is running and you try to sync, PhotoChooser crashes or something.
http://www.codeproject.com/Articles/342149/Using-WPConnect-instead-of-Zune-for-Windows-Phone
I figured that when synced, the photochooser instantiated inside the app is turned off or something, and stays so until the constructor is called again, which would happen if the app is re-launched.
Kinda peculiar though...
So, I'm getting fairly good at hooking and modifying classes, but this one is so unique, I'm not quite sure how to approach hooking it to do what I want. Code for the method/class I want to attack:
Code:
private class CreateLaunchPointListTask
extends AsyncTask<Void, Void, List<LaunchPoint>>
{
private CreateLaunchPointListTask() {}
protected List<LaunchPoint> doInBackground(Void... paramVarArgs)
{
paramVarArgs = mContext.getString(2131558445);
Object localObject = new Intent("android.intent.action.MAIN");
((Intent)localObject).addCategory(paramVarArgs);
paramVarArgs = new LinkedList();
PackageManager localPackageManager = mContext.getPackageManager();
localObject = localPackageManager.queryIntentActivities((Intent)localObject, 129);
int j = ((List)localObject).size();
int i = 0;
while (i < j)
{
ResolveInfo localResolveInfo = (ResolveInfo)((List)localObject).get(i);
if (activityInfo != null) {
paramVarArgs.add(new LaunchPoint(mContext, localPackageManager, localResolveInfo));
}
i += 1;
}
return paramVarArgs;
}
public void onPostExecute(List<LaunchPoint> arg1)
{
synchronized (mLock)
{
mAllLaunchPoints.clear();
mAllLaunchPoints.addAll(???);
synchronized (mCachedActions)
{
LaunchPointListGenerator.access$502(LaunchPointListGenerator.this, true);
if (!mCachedActions.isEmpty()) {
((LaunchPointListGenerator.CachedAction)mCachedActions.remove()).apply();
}
}
}
LaunchPointListGenerator.access$602(LaunchPointListGenerator.this, true);
Iterator localIterator = mListeners.iterator();
while (localIterator.hasNext()) {
((LaunchPointListGenerator.Listener)localIterator.next()).onLaunchPointListGeneratorReady();
}
}
}
So, while this is a big chunk of code, everything I want to do is really in the first few lines:
Code:
paramVarArgs = mContext.getString(2131558445);
Object localObject = new Intent("android.intent.action.MAIN");
((Intent)localObject).addCategory(paramVarArgs);
So, string 2131558445 is a specific intent. What I would like to do is add *another* category after 2131558445 is added to localObject.
That would be the simplest implementation.
A more advanced implementation would be to actually and return a second LinkedList, paramVarArgs2, that only matches up to the second intent category that we're inserting.
Any help would be greatly appreciated.