After a lot of search to find a solution to enable/disable the data connection without modifying the APN configuration, I finally found a solution that I would like to share with developers that are looking for the same thing.
I known that some applications (as Quick Settings) are able to do this but I was not able to find a solution on the web. Because I really wanted to have this feature in my AndroMax application, I searched how it is managed in the Android OS source code.
I quickly discovered that it's not possible to modifiy the connection state using the same API than what is used in the Android phone settings application because the necessary permission can only be obtained by a system application. After more investigation in Android source code, I discovered that it's possible to change the connection state with the ITelephony interface, using a permission that can be obtained by a standard application.
This solution is not working with Gingerbread due to security reenforcement, if anybody have a solution for Gingerbread, I buy it
Here is this solution:
Code:
import java.lang.reflect.Method;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
// Needs the following permissions:
// - "android.permission.MODIFY_PHONE_STATE"
public final class DataConManager
{
private TelephonyManager m_telManager = null;
private ConnectivityManager m_conManager = null;
// ------------------------------------------------------
// ------------------------------------------------------
public DataConManager(Context context)
{
try
{
// Get phone and connectivity services
m_telManager = (TelephonyManager)context.getSystemService("phone");
m_conManager = (ConnectivityManager)context.getSystemService("connectivity");
}
catch (Exception e)
{
m_telManager = null;
m_conManager = null;
}
}
// ------------------------------------------------------
// ------------------------------------------------------
boolean switchState(boolean enable)
{
boolean bRes = false;
// Data Connection mode (only if correctly initialized)
if (m_telManager != null)
{
try
{
// Will be used to invoke hidden methods with reflection
Class cTelMan = null;
Method getITelephony = null;
Object oTelephony = null;
Class cTelephony = null;
Method action = null;
// Get the current object implementing ITelephony interface
cTelMan = m_telManager.getClass();
getITelephony = cTelMan.getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
oTelephony = getITelephony.invoke(m_telManager);
// Call the enableDataConnectivity/disableDataConnectivity method
// of Telephony object
cTelephony = oTelephony.getClass();
if (enable)
{
action = cTelephony.getMethod("enableDataConnectivity");
}
else
{
action = cTelephony.getMethod("disableDataConnectivity");
}
action.setAccessible(true);
bRes = (Boolean)action.invoke(oTelephony);
}
catch (Exception e)
{
bRes = false;
}
}
return bRes;
}
// ------------------------------------------------------
// ------------------------------------------------------
public boolean isEnabled()
{
boolean bRes = false;
// Data Connection mode (only if correctly initialized)
if (m_conManager != null)
{
try
{
// Get Connectivity Service state
NetworkInfo netInfo = m_conManager.getNetworkInfo(0);
// Data is enabled if state is CONNECTED
bRes = (netInfo.getState() == NetworkInfo.State.CONNECTED);
}
catch (Exception e)
{
bRes = false;
}
}
return bRes;
}
}
isnt this same stuff as going
settings -> wireless & networks -> mobile networks - data service enable/disable ?
It has the same effect but it's at a low level since the API called by "settings -> wireless & networks -> mobile networks - data service enable/disable" is not permitted for a standard application.
Officicaly there is no API that can be use by an application to enable/disable data.
please help.. not working
Hi I have taken your class into my solution, the method switchState(true) returns true for me, but no data connection appears ... when I enable the data connection manually, the connection worx
I have set up the permissions correctly in my manifest...
any clues?
I guess that your data connection was not enabled at the beginning. This method only works is the connection state is enabled (system settings) and that you use it to disable/enable it.
It's like if you add a switch in addition to the system switch.
Sorry to drudge up an older thread. But I have a question that is related.
I have mastered the art of battery management with the Droid Bionic, and I think I've figured out an app that would help people manage their batteries throughout the day by giving quick, easy toggles that perform multiple connection state changes. Problem is, while I've done some development, it hasn't been Java.
Is this basically saying that there is no way to write an app that will allow you to selectively toggle data on or off (same as the Data Enabled toggle under Data Delivery), or control individual radio states?
Some app is turning on my data network even if I turn it off.Any idea?
Related
Hi, i'm currently exploring the gps on my device with the java api provided with the Android SDK.
I stumbled upon something that I can't make sense of: I collect the satellites my GPS sees and query those satellites it they are involved in the current fix and if they contain almanac and ephemeris data.
Now, somehow I never get a confirmation that the GPS i query contains eph or alm data? Turning on or off the aGPS don't really like to influence this. (FYI i'm running this on a Galaxy S)
I wonder, can someone try the attached program on his or her Android device and report back to me if the abbreviations "eph" and/or "alm" appear after the listed satellites.
Thanks in advance!
by request: code of the app (be warned this was my very first android app ):
Code:
package com.appelflap.android.location_app;
import java.util.Iterator;
import android.app.Activity;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.Location;
import android.location.GpsStatus;
import android.location.LocationListener;
import android.location.GpsStatus.Listener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class LocationActivity extends Activity implements LocationListener, GpsStatus.Listener {
private static final String TAG = "com.appelflap.android.location_app";
private LocationManager locationManager;
private static final String PROVIDER = "gps";
private TextView output;
private TextView accuracy;
private TextView gpsstatus;
private TextView gpsfix;
private TextView gps_output;
private TextView line;
private TextView maxSatellites;
private TextView maxLocked;
private TextView minSignalNoiseRatio;
private Integer iGpsStatus;
private Integer maxSats;
private Integer maxFix;
private Integer minSnr;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
maxSats = 0;
maxFix = 0; // maximal number of sats constituting a fix. The claim for the SGS is that this is always =< 8
minSnr = 100; // minimal Snr of a sat contained in a fix. The claim for the SGS is that this is always > 20 (Lets start set with an unreal high value)
iGpsStatus = -1 ;
output = (TextView) findViewById(R.id.output);
accuracy = (TextView) findViewById(R.id.accuracy);
line = (TextView) findViewById(R.id.line);
maxSatellites = (TextView) findViewById(R.id.maxSatellites);
maxLocked = (TextView) findViewById(R.id.maxLocked);
minSignalNoiseRatio = (TextView) findViewById(R.id.minSignalNoiseRatio);
gpsfix = (TextView) findViewById(R.id.gpsfix);
gpsstatus = (TextView) findViewById(R.id.gpsstatus);
gps_output = (TextView) findViewById(R.id.gps_output);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(PROVIDER, 0, 0, this);
locationManager.addGpsStatusListener(this);
}
private void registerLocationListeners() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(PROVIDER, 0, 0, this);
locationManager.addGpsStatusListener(this);
}
public void onLocationChanged(Location location) {
String result = String.format(
"Coordinates: latitude: %f, longitude: %f", location
.getLatitude(), location.getLongitude());
Log.d(TAG, "location update received: " + result);
output.setText(result);
accuracy.setText("Accuracy: " + location.getAccuracy());
}
public void onProviderDisabled(String provider) {
Log.d(TAG, "the following provider was disabled: " + provider);
}
public void onProviderEnabled(String provider) {
Log.d(TAG, "the following provider was enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, String.format(
"Provider status has changed. provider: %s, status: %d",
provider, status));
}
public void onGpsStatusChanged(int event)
{
Log.v("TEST","LocationActivity - onGpsStatusChange: onGpsStatusChanged: " + Integer.toString(event)) ;
int iSats;
int fix;
int snr;
switch( event )
{
case GpsStatus.GPS_EVENT_STARTED:
iGpsStatus = event ;
break ;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
GpsStatus xGpsStatus = locationManager.getGpsStatus(null) ;
Iterable<GpsSatellite> iSatellites = xGpsStatus.getSatellites() ;
Iterator<GpsSatellite> it = iSatellites.iterator() ;
iSats = 0 ; // Satellite Count
fix = 0 ; // Count satellites used in fix
StringBuilder s = new StringBuilder();
while ( it.hasNext() )
{
iSats++ ;
GpsSatellite oSat = (GpsSatellite) it.next() ;
s.append(oSat.getPrn());
s.append(": ");
snr = (int) oSat.getSnr();
s.append(snr);
s.append(" Snr");
if ( oSat.usedInFix() ) {
s.append(" (*) ");
fix++;
// if snr of this locked sat < minSnr then update minSnr
if (snr < minSnr) {
minSnr = snr;
minSignalNoiseRatio.setText("Min Snr: " + minSnr);
}
// Just testing for ephemeris and almanac data. On the Galaxy S the following GpsSatelite methods
// always return "false". To do: formatting the output..
}
if ( oSat.hasEphemeris() ) {
s.append(" Eph ");
}
if ( oSat.hasAlmanac() ) {
s.append(" Alm ");
}
s.append("\n");
Log.v("TEST","LocationActivity - onGpsStatusChange: Satellites: " + oSat.getSnr() ) ;
}
gpsstatus.setText("Satellites: " + iSats);
gpsfix.setText("Locked: " + fix);
Log.v("TEST","LocationActivity - onGpsStatusChange: Satellites: " + iSats ) ;
if ( s.length() > 0) {
gps_output.setText(s.toString());
}
else { gps_output.setText("Waiting..."); }
if ( iSats > maxSats ) {
maxSats = iSats;
maxSatellites.setText("Max Sats: " + maxSats);
}
if ( fix > maxFix ) {
maxFix = fix;
maxLocked.setText("Max Locked: " + maxFix);
}
break ;
case GpsStatus.GPS_EVENT_FIRST_FIX:
iGpsStatus = event ;
break ;
case GpsStatus.GPS_EVENT_STOPPED:
gpsstatus.setText("Stopped...") ;
iGpsStatus = event ;
break ;
}
}
protected void onPause() {
// Make sure that when the activity goes to
// background, the device stops getting locations
// to save battery life.
locationManager.removeUpdates(this);
super.onPause();
}
protected void onResume() {
// Make sure that when the activity has been
// suspended to background,
// the device starts getting locations again
registerLocationListeners();
super.onResume();
}
}
// Framework for the code based on http://www.hascode.com/2010/05/sensor-fun-location-based-services-and-gps-for-android/
bumperdibump
LocationApp could not be installed on this phone.
System Requirements? I'm running Android 1.6
t-bon3 said:
LocationApp could not be installed on this phone.
System Requirements? I'm running Android 1.6
Click to expand...
Click to collapse
I attached another version for all Android levels. I checked with the api docs and it should run.
Thank you very much for testing!
I get a list of saetllites with a number, 'Snr' then a (*) for the sats that have a lock, but nothing else, no 'Eph' or 'Alm'.
This is on Android 1.6 on an i-mobile i858 device.
Do you have sample code for a simple app that reads data from the GPS. GPS software from the market seems buggy on my device and I would like to investigate by writing my own basic GPS app.
Thanks.
t-bon3 said:
I get a list of saetllites with a number, 'Snr' then a (*) for the sats that have a lock, but nothing else, no 'Eph' or 'Alm'.
This is on Android 1.6 on an i-mobile i858 device.
Do you have sample code for a simple app that reads data from the GPS. GPS software from the market seems buggy on my device and I would like to investigate by writing my own basic GPS app.
Thanks.
Click to expand...
Click to collapse
No problem, I will clean up the code somewhat and will put it up in the first post.
BTW did you activated aGPS while testing the app?
On my device under "My Location" in settings there are only these options:
Use wireless networks
Enable GPS satellites
Share with Google
I had all 3 set to active while testing the app.
t-bon3 said:
On my device under "My Location" in settings there are only these options:
Use wireless networks
Enable GPS satellites
Share with Google
I had all 3 set to active while testing the app.
Click to expand...
Click to collapse
The aGPS function has to be activated in an app delivered with your device. Don't know if it is activated by default. (assuming your GPS chip supports aGPS of course)
Anyway, I put the code up in the first post. (EDIT: included the resource files and the manifest file in a attached zip file)
EDIT: Development continued Working hard
Hello everyone
I'm trying to port my WIP Infosode from Android (Adobe AIR) to Windows Phone 7, and I have some big problems figuring out how to access a remote XML service, in this case http://services.tvrage.com/
I've used Visual Basic .NET for both desktop and Windows Mobile applications and now for WP7, so I got some VB.NET experience.
Any help is appreciated and will be noted in the finished application.
Regards
//
IzaacJ
Here is one somewhat dirty way.
Download your data (xml) into the isolated storage. After that process the xml file stored.
Code:
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://path.to/the/" + item + ".xml/"));
static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// If we have results
if (!string.IsNullOrEmpty(e.Result))
{
#region Save to Isolated Storage
try
{
// Isolated Storage Directory
string xmlStorageDirectory = "Profiles";
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
// File Path
string filePath = Path.Combine(xmlStorageDirectory, String.Format("{0}.xml", ActiveID));
// Check if the Directory exists. If not create it
if (!store.DirectoryExists(xmlStorageDirectory))
{
store.CreateDirectory(xmlStorageDirectory);
}
// Use Isolated Storeage to write the file
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store))
{
// Use the stream to write the file
using (StreamWriter stream = new StreamWriter(fileStream))
{
stream.Write(e.Result.Replace(" & ", " & "));
}
}
}
}
// OMG EXCEPTIONS :(
catch (IsolatedStorageException exception)
{
throw exception;
}
#endregion
#region Reading
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var file = appStorage.OpenFile("Profiles/" + ActiveID + ".xml", FileMode.Open))
{
XmlReader reader = XmlReader.Create(file);
CharacterDataModel profile = new CharacterDataModel();
List<PlayerTraitsModel> traits = new List<PlayerTraitsModel>();
PlayerTraitsModel trait = new PlayerTraitsModel();
bool isCdata = false;
bool isPdata = false;
// While we read the data
while (reader.Read())
{
#region Character
if (reader.Name == "cdata") isCdata = true;
if (isCdata)
{
if (reader.NodeType == XmlNodeType.Element)
{
#region Check for the following values and shallow copy that to the model
//string item = reader.ReadElementContentAsString();
switch (reader.Name)
{
case "id":
profile.id = reader.ReadElementContentAsString();
break;
}
#endregion
}
}
if (reader.NodeType == XmlNodeType.EndElement && reader.Name.Contains("cdata"))
isCdata = false;
#endregion
}
}
}
#endregion
}
}
Thanks for that
Will try to adopt it to VB.NET and see if it will work
At least it's something that I could use until I find a better way.
Regards
Hi,
Use the OpenReadCompleted event of the WebClient, and then put the result into an XDocument by using an XmlReader; from there it's easy to process it (using LINQ to XML) without having to store the XML anywhere first (i.e. do it all in memory). Here's kind of how I do it C#.
Code:
WebClient client = new WebClient();
// Set up the 'completed' event before loading anything
client.OpenReadCompleted += (sender, e) =>
{
if (e.Error != null)
{
if (e.Error is WebException)
{
... Either a connection error, or an invalid status code has been returned. You can determine which using code.
}
else
... // some other exception
return;
}
// Turn the result into an XDocument and parse using LINQ
try
{
Stream aStream = e.Result;
XmlReader anXmlStream = XmlReader.Create(aStream);
XDocument ourXDocument = XDocument.Load(anXmlStream);
// Parse the XML here - best to use 'Linq to XML' to do it
List<TvShow> TVShows = from aShow in ourXDocument.Descendants("show")
select new TvShow() {
ShowName = aShow.Element("name").Value,
Link = aShow.Element("link").Value
};
//////////////////
str.Close();
// if here it all went to plan
}
catch (XmlException xe)
{
...
}
catch (Exception ge)
{
...
}
};
// Here's the bit that actually sets it going
try
{
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));
}
catch (OutOfMemoryException)
{
... Handle the exception
}
catch (StackOverflowException)
{
... Handle the exception
}
catch (Exception ge)
{
... Handle the exception
}
If you're doing this kind of thing a lot it's good to set it up as reusable class that either has it's own events (e.g. ItemsLoaded, ErrorOccured, and ProcessItems) that can be subscribed to, or if you prefer you can have them as methods to override so that you can use it as a web service loading base class from which you can inherit.
Hope that helps. Good luck with it
Ian
otherworld said:
Hi,
Use the OpenReadCompleted event of the WebClient, and then put the result into an XDocument by using an XmlReader; from there it's easy to process it (using LINQ to XML) without having to store the XML anywhere first (i.e. do it all in memory). Here's kind of how I do it C#.
Code:
WebClient client = new WebClient();
// Set up the 'completed' event before loading anything
client.OpenReadCompleted += (sender, e) =>
{
if (e.Error != null)
{
if (e.Error is WebException)
{
... Either a connection error, or an invalid status code has been returned. You can determine which using code.
}
else
... // some other exception
return;
}
// Turn the result into an XDocument and parse using LINQ
try
{
Stream aStream = e.Result;
XmlReader anXmlStream = XmlReader.Create(aStream);
XDocument ourXDocument = XDocument.Load(anXmlStream);
// Parse the XML here - best to use 'Linq to XML' to do it
List<TvShow> TVShows = from aShow in ourXDocument.Descendants("show")
select new TvShow() {
ShowName = aShow.Element("name").Value,
Link = aShow.Element("link").Value
};
//////////////////
str.Close();
// if here it all went to plan
}
catch (XmlException xe)
{
...
}
catch (Exception ge)
{
...
}
};
// Here's the bit that actually sets it going
try
{
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));
}
catch (OutOfMemoryException)
{
... Handle the exception
}
catch (StackOverflowException)
{
... Handle the exception
}
catch (Exception ge)
{
... Handle the exception
}
If you're doing this kind of thing a lot it's good to set it up as reusable class that either has it's own events (e.g. ItemsLoaded, ErrorOccured, and ProcessItems) that can be subscribed to, or if you prefer you can have them as methods to override so that you can use it as a web service loading base class from which you can inherit.
Hope that helps. Good luck with it
Ian
Click to expand...
Click to collapse
Thanks
I'm building a class with functions for fetching and storing the returned XML requests.
It's smart to store it in the IsoStorage so that the data is available offline as well and it will only download the new XML's if it's updated on the server
I think it will make the application a bit more useful.
Regards
EDIT: I've tried to port the first example from MJCS to VB.Net without success. The app closes itself when it's supposed to search and get results from the server. The URL to the generated XML (including parameters) is http://services.tvrage.com/feeds/search.php?key=[MY_API_KEY]&show=[SHOW_NAME]
The code as for now is this:
Code:
Public Function Search(ByVal SearchString As String) As String
Dim Url As New Uri(XMLUrl & "feeds/search.php?key=" & APIKey & "&show=" & SearchString)
'XMLUrl = http://services.tvrage.com/
'APIKey = My API key from TVRage.com
'SearchString = The showname to be searched for in the database
XML.DownloadStringAsync(Url)
Return 0
End Function
Any ideas?
Regards
I want to control the PC cursor by WP7, so I try to use the ManipulationDelta in WP7 that can help me to calculate the difference between he star tap and the end tap
Code:
public MainPage()
{
InitializeComponent();
this.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(MainPage_ManipulationDelta);
transformG = new TransformGroup();
translation = new TranslateTransform();
transformG.Children.Add(translation);
RenderTransform = transformG; // you see I don't use any transform here because I don't know where I put. If I use the image.RenderTransform of it will move also for the screen of WP if I put this.RenderTransform, So anyone have a solution
SenderSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
void MainPage_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
startX = e.ManipulationOrigin.X;
startY = e.ManipulationOrigin.Y;
DeltaX = e.DeltaManipulation.Translation.X;
DeltaY = e.DeltaManipulation.Translation.Y;
translation.X += e.DeltaManipulation.Translation.X;
translation.Y += e.DeltaManipulation.Translation.Y;
EndX = Convert.ToDouble(translation.X);
EndY = Convert.ToDouble(translation.Y);
}
I am juste want to send DeltaX and DeltaY to the server to calculate them to the mouse position in the screen, So I write this code
Code:
void StartSending()
{
while (!stop)
try
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
byte[] buffer = Encoding.UTF8.GetBytes(DeltaX.ToString() + "/" + DeltaY.ToString());
socketEventArg.SetBuffer(buffer, 0, buffer.Length);
SenderSocket.SendToAsync(socketEventArg);
}
catch (Exception) { }
}
I concatenate them in 1 buffer with separate by "/" and in server I use this code to separate
Code:
void Receive(byte[] buffer)
{
string chaine = "";
if (SenderSocket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
chaine = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
chaine.Trim('\0');
string[] pos = chaine.Split('/');
for (int i = 0; i < pos.Length; i++)
{
pX = Convert.ToInt32(pos[0]);
pY = Convert.ToInt32(pos[1]);
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X + pX, Cursor.Position.Y + pY);
}
}
else
{
}
});
SenderSocket.ReceiveFromAsync(socketEventArg);
}
Just I want to control the cursor, if you have any other methods so plz help me and I am really grateful
Didn't you already have a thread about this? Please re-use existing threads instead of starting new ones. Even if it wasn't you, *somebody* was working on this problem already, and very recently. Always use the Search button before starting a thread.
So... what are you looking for from us? Does your current code work? If not, in what way does it fail? Without knowing what your question is, we can't provide answers.
If you want some advice, though...
Sending as strings is very inefficient on both ends; it would be better to use arrays (which you could convert directly to byte arrays and back again).
You're sending as TCP, which is OK but probably not optimal. For this kind of data, UDP is quite possibly better. If nothing else, it provides clearly delineated packets indicating each update.
Hi, i am trying to write a application that can be used for streaming my phone to my windows desktop running a Java client to receive the images. However when i tried to create a background task following a tutorial by microsoft i am unable to access the UIElement. Does anyone know how to work around this?
the below code in the OnInvoke is able to run in a application however if i were to create it under a Task Agent project , i cant because i cant get the FrameElement.
Code:
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
/// <remarks>
/// ScheduledAgent constructor, initializes the UnhandledException handler
/// </remarks>
public ScheduledAgent()
{
if (!_classInitialized)
{
_classInitialized = true;
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
});
}
}
/// Code to execute on Unhandled Exceptions
private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
var timer = new System.Windows.Threading.DispatcherTimer
{
Interval = System.TimeSpan.FromSeconds(10)
};
timer.Tick += (sender, args) =>
{
Microsoft.Devices.VibrateController.Default.Start(
TimeSpan.FromSeconds(0.1));
var bitmap = new System.Windows.Media.Imaging.WriteableBitmap(this.Parent, null);
var stream = new System.IO.MemoryStream();
System.Windows.Media.Imaging.Extensions.SaveJpeg(bitmap, stream,
bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
stream.Position = 0;
var mediaLib = new Microsoft.Xna.Framework.Media.MediaLibrary();
var datetime = System.DateTime.Now;
var filename =
System.String.Format("Capture-{0}-{1}-{2}-{3}-{4}-{5}",
datetime.Year % 100, datetime.Month, datetime.Day,
datetime.Hour, datetime.Minute, datetime.Second);
mediaLib.SavePicture(filename, stream);
};
timer.Start();
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
kyrogue said:
i am unable to access the UIElement
Click to expand...
Click to collapse
Hmm... Background agents don't have UIElements at all (and by the sandbox concept you can't access anything not belong to your app).
To capture WP7 screen, you should have an interop-unlock phone and use DllImport library.
Interop-unlock is *not* required to use anything in DllImport, actually - normal dev-unlock works fine.
There actually used to be an app that did what you described (stream the screen contents to a PC in real-time) but I don't think it ever got updated to work on Mango.
This is a dumper thread for collecting research and development information on reversing some (or all) of the various Samsung proprietary Applications and binaries found in their later top models running at least 4.2.2, and preferably also SELinux enabled as Enforcing.
In these devices there is an extensive amount of hidden functions, applications and behind the scenes modifications that is completely outside anything that we will ever be able to find in the AOSP repositories. In addition Samsung is spending more energy into obfuscating many of these functions and applications, which makes security vulnerability research much harder. Why? What is it that they try to hide from public scrutiny?
So if you have any insights or are particularly good at reading obtuse OEM Java code. Please join the discussion and help us out.
One of the first Apps to look at is the Samsung ServiceMode apps. There are at least three of them.
1) serviceModeApp_FB.apk
2) serviceModeApp_RIL.apk
3) Samsungservice.apk
Let's have a look at the first one: serviceModeApp_FB.apk
The first thing that hits you in the face is the LibOTPSecurity. This class is using the time zone as a mechanism for obfuscating some security mechanism using OTP (One Time Password) as a means of temporary authorization for access. (Thanks @ryanbg) The code look like this:
Code:
[SIZE=2]package LibOTPSecurity;
import ibOTPSecurity.OTPSecurit;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class OTPSecurity
{
private String GetDateString(int paramInt)
{
Calendar localCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
localCalendar.add(12, paramInt * -1);
return new StringBuilder(String.valueOf(new StringBuilder(String.valueOf(new StringBuilder(String.valueOf(new DecimalFormat("00").format(-2000 + localCalendar.get(1)))).append(new DecimalFormat("00").format(1 + localCalendar.get(2))).toString())).append(new DecimalFormat("00").format(localCalendar.get(12))).toString())).append(new DecimalFormat("00").format(localCalendar.get(5))).toString() + new DecimalFormat("00").format(localCalendar.get(11));
}
private int MakeHashCode(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
if (i < 0)
i *= -1;
return i;
}
i = i + (i << 5) + paramString.charAt(j);
}
}
public boolean CheckOTP(String paramString1, String paramString2)
{
int j;
for (int i = 5; ; i = j)
{
j = i - 1;
if (i <= -1)
return false;
if (paramString1.equalsIgnoreCase(Integer.toString(MakeHashCode(paramString2 + GetDateString(j)))))
return true;
}
}
}
[/SIZE]
This is making a "hash" out of some date strings for comparison. hopefully we'll see later what exactly these strings come from.
The GetDateString function can be reformatted as:
Code:
[SIZE=2] private String GetDateString(int paramInt) {
Calendar localCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
localCalendar.add(12, paramInt * -1);
return new StringBuilder(String.valueOf(new StringBuilder(String.valueOf(new StringBuilder(String.valueOf(new DecimalFormat("00")
.format(-2000 + localCalendar.get(1))))
.append(new DecimalFormat("00")
.format(1 + localCalendar.get(2)))
.toString()))
.append(new DecimalFormat("00")
.format(localCalendar.get(12)))
.toString()))
.append(new DecimalFormat("00")
.format(localCalendar.get(5)))
.toString() + new DecimalFormat("00")
.format(localCalendar.get(11));
}[/SIZE]
I'd have been much happier if this was simplified to readable pseudo-code.
Another interesting part is the SysDump.class:
Code:
[SIZE=2] private boolean checkForNoAuthorityAndNotEngBuild()
{
this.settings = getSharedPreferences("SYSDUMPOTP", 0);
boolean bool = this.settings.getBoolean("ril.OTPAuth", false);
String str = String.valueOf(SystemProperties.get("ro.build.type"));
if ((!bool) && (str.compareToIgnoreCase("eng") != 0))
{
Log.e("SysDump", "It's user binary");
return true;
}
Log.e("SysDump", "It's eng binary");
return false;
}
[/SIZE]
This clearly (!) determines whether or not your phone is currently set as an Engineering model or User model. To allow this you probably need to set these properties:
Code:
ro.build.type=eng
ril.OTPAuth=true
It's possible that OTP = One Time Password as a means of temporary authorization for accessing service/engineering features. It could be similar to the Blackberry engineering menu that is accessed by a code generated from the Date/Time and device specific information. I'm also doing some significant work on disassembling these applications. Major developments will be posted here.
fusedlocation.apk
is this [fusedlocation.apk] a samsung thing?
disabling/removing/dummyfile all cause reboot like failing critical service.
this has been bothering me for sometime. there is literally no intelligent information
i've been able to find on this. that killing it skunks the os suggest that it's not so simple
as "oh yeah derrr that's for gps or sumthin.."
i could go on but, that's the basics of it.
do you have a list of suspect or confirmed scummy files/bin/apks?
thanks
m