[MOD] SMS Backgroud task sample - Windows 8 Development and Hacking

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

Related

C# Battery State

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

Closing gps in gps event handler - endless loop

In my application when I get position latitude and longitude from GPS, I am downloading bing map to a picture box. I've been trying now to protect my application in case there is no internet connection. I've done that in the GetMap function and it works fine. After that I want to close gps - the problem is that I'm trying to do that in gps event handler - it is so because I update the picture box constantly:
Code:
void UpdateData(object sender, System.EventArgs args)
{
menuGPS.Text = "Enable GPS";
menuZoom.Enabled = false;
menuView.Enabled = false;
}
void gps_LocationChanged(object sender, Microsoft.WindowsMobile.Samples.Location.LocationChangedEventArgs args)
{
if (args.Position.LatitudeValid && args.Position.LongitudeValid)
{
if (isCameraEnabled == false)
{
try
{
pbMap.Invoke((UpdateMap)delegate()
{
pbMap.Image = bingMap.GetMap(args.Position.Latitude,
args.Position.Longitude,
zoom,
mapStyle);
});
if (pbMap.Image == null)
{
Invoke(updateDataHandler);
gpsData.gps.LocationChanged -= gps_LocationChanged;
gpsData.closeGPS();
}
}
catch (ArgumentException ex)
{
MessageBox.Show("An error has occured:" + ex.Message , "Error");
}
}
else
{
}
}
}
So after the gpsData.gps.LocationChanged -= gps_LocationChanged; and gpsData.closeGPS(); are being called in the event handler the gps gets stuck in the WaitForGpsEvents() method in GPS.cs in the while loop because bool lisening value is not changed to false.
If I put gpsData.gps.LocationChanged -= gps_LocationChanged; and gpsData.closeGPS(); to the void UpdateData(object sender, System.EventArgs args) then it stops in the Close() method on the lock condition:
// block until our event thread is finished before
// we close our native event handles
lock (this)
How can I close the GPS?

Photochooser task not working after phone was synced with PC?

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...

Galaxy S3 ver 4.1.1 - Trying to start Activity from Emergency Dialer after placeCall

We are working with a Galaxy S3 (Android 4.1.1). We are able to get the activity from param.thisObject and change the title by getting the activity and calling setTitle(), but when we want to start a new activity, the activity doesn't start. Does anyone know how to spawn a new activity?
Our code is building off of SmileyClock in the tutorial.
Main.java
---------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.example.SmileyClock;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import android.aMain.javapp.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
public class Main implements IXposedHookLoadPackage {
@override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
// TODO Auto-generated method stub
if (!lpparam.packageName.equals("com.android.phone"))//check if the package being loaded is systemUI
return;
//All code here is only called if it is indeed SystemUI
findAndHookMethod("com.android.phone.EmergencyDialer", lpparam.classLoader, "placeCall", new XC_MethodHook() {
@override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
Activity emergencyDialer = (Activity) param.thisObject;
emergencyDialer.setTitle("Title has been changed!");
Intent newIntent = new Intent(emergencyDialer, BlackScreenActivity.class);
newIntent.addFlgags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
emergencyDialer.startActivity(newIntent);
Activity emergencyDialer = (Activity) param.thisObject;
Object[] args = param.args;
View view = (View) args[0];
emergencyDialer.setTitle("" + view.getId());
Intent newIntent = new Intent(Intent.ACTION_VIEW, null, emergencyDialer, BlackScreenActivity.class);
emergencyDialer.startActivity(newIntent);
}
});
}
}
BlackScreenActivity.java
---------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.example.SmileyClock;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class BlackScreenActivity extends Activity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_black_screen);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.activity_black_screen);
try {
Thread.sleep(3000);
finish();
Log.v("Xposed", "Sleep is done");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("ERROR CATCH THING", e.toString());
}
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.black_screen, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Hooking a protected List in an Inner Class with an odd set of Parameters

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.

Categories

Resources