home screen widget ui problem - General Questions and Answers

Hello,
i created a widget that uses a service with wakelock to update and parse data from an xml and update the widget's ui so that items would rotate every few seconds (standard news feed widget).
the problem is that the ui stops updating after a few hours although the data keeps updating.
here's the code i am using to update the ui
Code:
mUpdateTimeTask = null;
mUpdateTimeTask = new Runnable()
{
public void run()
{
if(which_item+1 < Widget_titles.length)
which_item++;
else
which_item = 0;
if(Widget_which_item_ed != null)
{
Widget_which_item_ed.putInt("WIDGET_WHICH_ITEM", which_item);
Widget_which_item_ed.commit();
}
else
{
Widget_which_item = context.getSharedPreferences("WIDGET_WHICH_ITEM", Context.MODE_WORLD_WRITEABLE);
Widget_which_item_ed = Widget_which_item.edit();
Widget_which_item_ed.putInt("WIDGET_WHICH_ITEM", which_item);
Widget_which_item_ed.commit();
}
updateViews.setTextViewText(R.id.WidgetText, Widget_titles[which_item]);
updateViews.setTextViewText(R.id.WidgetPostTime, rightNow.get(Calendar.MONTH)+"/"+rightNow.get(Calendar.DATE)+"/"+rightNow.get(Calendar.YEAR));
manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(WidgetId, updateViews);
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(this, widget_interval * 1000);
}
};
mHandler.postDelayed(mUpdateTimeTask, widget_interval * 1000);
Log.i(TAG, "sliding update handler was configed");
i am really stuck and could really use help
Edit:
i managed to go around this problem by implementing the BroadCastReciever for the screen on/off intents as shown in a tutorial i found (i can't post it here - the forum won't let me-sorry)
and therefore the amount of time that the widget needs to run is much smaller.

Related

A solution to enable/disable data connection without modifying APN

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?

[Q][VB.NET] Access remote XML services

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

Capturing Screenshots using background agent WP7.1

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.

[Bug Fix] Contacts Bug - Merry Christmas!

Hello all,
Looks like I have managed to fix this bug. Here is the code.
//android/packages/apps/Contacts/src/com/android/contacts/datepicker/DatePicker.java
if (months[0].startsWith("1")) {
for (int i = 0; i < months.length; i++) {
months = String.valueOf(i + 1);
}
//mMonthPicker.setMinValue(1); //-----------------------------------------------------------> setMinValue should be 0
mMonthPicker.setMinValue(0);
mMonthPicker.setMaxValue(12);
} else {
//mMonthPicker.setMinValue(1); //-----------------------------------------------------------> setMinValue should be 0
mMonthPicker.setMinValue(0);
mMonthPicker.setMaxValue(12);
mMonthPicker.setDisplayedValues(months);
}
mMonthPicker.setOnLongPressUpdateInterval(200);
mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
/* We display the month 1-12 but store it 0-11 so always
* subtract by one to ensure our internal state is always 0-11
*/
//mMonth = newVal - 1; //----------------------------------------------------------->should be newVal
mMonth = newVal;
// Adjust max day of the month
adjustMaxDay();
notifyDateChanged();
updateDaySpinner();
}
});
You can test the apk attached
still not perfect, just an immediate solution so that you do not miss the Christmas!!!
-Adarsh
adarshahd said:
Hello all,
Looks like I have managed to fix this bug. Here is the code.
//android/packages/apps/Contacts/src/com/android/contacts/datepicker/DatePicker.java
if (months[0].startsWith("1")) {
for (int i = 0; i < months.length; i++) {
months = String.valueOf(i + 1);
}
//mMonthPicker.setMinValue(1); //-----------------------------------------------------------> setMinValue should be 0
mMonthPicker.setMinValue(0);
mMonthPicker.setMaxValue(12);
} else {
//mMonthPicker.setMinValue(1); //-----------------------------------------------------------> setMinValue should be 0
mMonthPicker.setMinValue(0);
mMonthPicker.setMaxValue(12);
mMonthPicker.setDisplayedValues(months);
}
mMonthPicker.setOnLongPressUpdateInterval(200);
mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
/* We display the month 1-12 but store it 0-11 so always
* subtract by one to ensure our internal state is always 0-11
*/
//mMonth = newVal - 1; //----------------------------------------------------------->should be newVal
mMonth = newVal;
// Adjust max day of the month
adjustMaxDay();
notifyDateChanged();
updateDaySpinner();
}
});
You can test the apk attached
still not perfect, just an immediate solution so that you do not miss the Christmas!!!
-Adarsh
Click to expand...
Click to collapse
nice work sir!
Not sure if you could help with another contact issue. This does not seam as though it is a bug. But more like a feature that was left out. I am on JB though it is a CM ROM. But it happened on a factory JB firmware also. When I go to enter a new contact I am given the options to choose an email address to link it to. On ICS we had the option of choosing the phone to link to. That has gone. I refuse to link my contacts to Google. So therefore I can not enter new contacts. Can you suggests how to implement the phone as an option again? If not, where should I go to try and resolve this? Another thing, I don't want to link to an email account and just not sync.
Sent from my SCH-I535 using xda app-developers app

Why my items are not redrawn after invoking `invalidateViews()` ?

Why my items are not redrawn after invoking `invalidateViews()` ?
I ask because i try to refresh `listItems` after a bg-thread notify an image rsc was downloaded.
But nothing is updated. Only after exiting and re-entering the new icons are drawn.
I have an activity with `adapter` of type `SettingValueAdapter extends BaseAdapter`
it has a member:
`private SettingsValue[] values;`
it has two interesting methods:
@override
public View getView(int position, View view, ViewGroup parent) {
AddressItem ai= (AddressItem)getItem(position);
DriveToNativeManager dnm = DriveToNativeManager.getInstance();
if (view == null) {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.address_item, null);
}
view.setTag(R.id.addressItem,ai);
view.setTag(position);
view.findViewById(R.id.fullAddressItemCol).setVisibility(View.VISIBLE);
view.findViewById(R.id.addressItemTouch).setVisibility(View.GONE);
view.findViewById(R.id.addressItemImage).setVisibility(View.GONE);
if (ai != null) {
...
}
view.findViewById(R.id.addressItemIconLayout).setVisibility(View.VISIBLE);
Drawable icon = ResManager.GetSkinDrawable(ai.getIcon() + ".bin");
((ImageView)view.findViewById(R.id.addressItemIcon)).setImageDrawable(icon);
..
}
I attach a callback to the bg-thread (c language) image downloading process.
The callback switches to the ui-thread and calls this `refreshList`:
public void refreshSearchIconsOnSearchActivity() {
Runnable refreshViewEvent = new Runnable() {
@override
public void run() {
Activity currentActivity = AppService.getActiveActivity();
if (currentActivity instanceof SearchActivity) {
Log.d("w", "refreshSearchIconsOnSearchActivity callback running in thread "
+ Thread.currentThread().getId() );
//results list
((SearchActivity) currentActivity).refreshList();
}
}
};
AppService.Post(refreshViewEvent);
}
However, the images are done downloading and are not refreshed on the activity.
They are refreshed only when I leave an re-enter the activity.
What am I missing?

Categories

Resources