[Q] Best way to use threads in services - Java for Android App Development

I'm new to Android development and haven't used threads in Java before. I have a foreground Service, and I want to perform network operations periodically. I know that I have to do this on another thread, but what is the best way to start one? I've found many ways to do it but I am not sure of which to use: should I use AsyncTask, IntentService, Threads and Handlers, or just a Thread and a Runnable?

I would use async task, it is quite easy to use
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

asynctask or just thread directly.
Sent from my Nexus 5 using XDA Free mobile app

simplegoodmobile said:
asynctask or just thread directly.
Sent from my Nexus 5 using XDA Free mobile app
Click to expand...
Click to collapse
If you want to perform periodic background work (e.g. poll some web service every X minutes), the best and most reliable way would be to use AlarmManager.
Services can be killed at any time by android systems, and in some scenarios foreground services can be killed to.
Have a look at this documentation on Scheduling Repeating Alarms.

I would use Asynctask as mentioned before, it is easy to handle, here is an example, edit as appopriate (doInBackground is your main method where you execute the service's code)
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}

Related

(DEV STARTED) Full-screen DirectX Mobile on Touch Pr

I'm just going crazy trying to get full-screen mode to work with the Touch Pro. Windowed mode works as expected (black screen, or whatever color I Clear to), but full-screen just does nothing at all. No exceptions are thrown (all the calls are supposedly working fine), but all I see on the screen is the white form background.
I'm using C# and DirectX Mobile. The project is targeting Windows Mobile 6 Professional. Here's the entire code of the only source file in the project:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using Microsoft.WindowsMobile.DirectX;
namespace Tilt {
public class frmMain : Form {
[MTAThread]
static void Main() {
frmMain f = new frmMain();
f.InitializeGraphics();
f.Show();
while (f.Created) {
f.Render();
Application.DoEvents();
}
f.DisposeGraphics();
}
public Device device;
public bool Created;
protected bool InitializeGraphics() {
Created = true;
PresentParameters p = new PresentParameters();
p.SwapEffect = SwapEffect.CopyVSync;
p.Windowed = true;
/*
* For some reason, these settings allow the device to be created,
* but nothing gets drawn (the form's white background is just shown
* full-screen). WTFmate?
DisplayMode dm = Manager.Adapters.Default.CurrentDisplayMode;
p.Windowed = false;
p.BackBufferWidth = dm.Width;
p.BackBufferHeight = dm.Height;
p.BackBufferFormat = dm.Format;
*/
device = new Device(0, DeviceType.Default, this, CreateFlags.None, p);
return true;
}
protected void Render() {
device.Clear(ClearFlags.Target, Color.Black, 1.0F, 0);
device.BeginScene();
device.EndScene();
device.Present();
}
protected void DisposeGraphics() {
device.Dispose();
}
}
}
Any help would be greatly appreciated!
I edited the name on this so that it wouldn't get moved to the Q&A Section on accident.

Application Request for Weight Watchers Points Calculator

Can someone make a .cab or an .exe program to calculate Weight Watchers points? I found this article on the internet where it looks like someone as already done it but they did not post it. Here is the article
http://geekswithblogs.net/cdahlinge...-mobile-meets-weight-watchers--mvp-style.aspx
Craig Dahlinger
<< Presenting at Richdmond code camp 2008.2 | Home | mshtml – the ongoing adventure >> windows mobile meets weight watchers : MVP style Ok, so I know it has been a long time since a post, but it has been really busy with work and family. I have been busy coding and learning lots of new stuff. I work with a great bunch of developers and my current team lead is a great mentor.
Well for the new year the wife and I decided to get back into shape. I started hitting the gym and so did she but she is also doing weight watchers with a friend. One of the things they do is they have to calculate points on a daily basis. These points are comprised of calories, fat and fiber. There is a formula for these three which in turn results in the number of points a particular item is. A few months ago I convinced the wife to get a windows mobile device (woo hoo!) and she is a good power user. So one night she asks me, β€œIs there a way I can just enter in the calories, fat and fiber on my phone and it tell me how many points something is?”. I did some searching and there are numerous online versions of the calculator but no native ones for windows mobile. I found the formula here, and started to get to work.
I wanted to approach this application using the MVP design pattern. I know it may be overkill for this simple of an application but I thought it would be good practice.
I started with the interface for the data model, in this case it would be the main caloric properties of food.
namespace WWPC.Common.Interfaces{ public interface IFoodModel { int Fiber { get; set; } int Calories { get; set; } float Fat { get; set; } int Points { get; set; } int CalculatePoints(); }}I then wrote up the interface for the view for the model.
namespace WWPC.Common.Interfaces{ public interface IFoodCalcView { int Calories { get; } int Fiber { get; } float Fat { get; } int Points { set; } event EventHandler DataChanged; }}Next, came the interface for the presenter.
public interface IFoodCalcPresenter { void OnCalculatePoints(); }
Ok, now that I got my main interfaces in place, time to code up the implementation. I started with the model first since this was the class that would provide the implementation for calculating the caloric points. Using the formula mentioned above, the CalculatePoints() method came out like so:
public int CalculatePoints(){ var calories = Convert.ToDecimal(Calories); var cal = calories / 50; var totalFat = Convert.ToDecimal(Fat); var fat = totalFat / 12; var fiber = Convert.ToDecimal(Fiber); return Points = Convert.ToInt32(Math.Round(cal + fat - (fiber/5), 0)); } With the model complete, I then moved to the presenter. The presenter would be responsible for binding the model to the view responding to the data changes in the view and rebinding those changes to the model. I made the presenter with an overloaded constructor to take a view and a model. The presenter then binds to the data changed event on the view which enables the presenter to update the model from the view. The OnCalculatePoints() method will update the view with the points value after using the model for calculation.
namespace WWPC.Common{ public class FoodPresenter : IFoodCalcPresenter { private readonly IFoodCalcView _View; private readonly IFoodModel _Model; public FoodPresenter(IFoodCalcView view, IFoodModel model) { _View = view; _View.DataChanged += new EventHandler(_View_DataChanged); _Model = model; } void _View_DataChanged(object sender, EventArgs e) { SetModelFromView(); } private void SetModelFromView() { _Model.Calories = _View.Calories; _Model.Fat = _View.Fat; _Model.Fiber = _View.Fiber; } #region IFoodCalcPresenter Members public void OnCalculatePoints() { _View.Points = _Model.CalculatePoints(); } #endregion }}
With the presenter done it was time to implement the view. I wanted a simple mobile form where you can enter in data quickly and then calculate the results. I initially tried using a label to display the result, but did not like it. I then tried a mobile gauge control, but that took up too much space on the small screen. Finally I decided to use the notification class for windows mobile. I did not use the managed wrapper version, I used the the version created by Christopher Fairbairn, found here. This version has an awesome implementation which exposes many features of the notification class. I wanted to give the user the ability to dismiss the notification when they were done reading the results. Also using the notification class the UI was able show the needed text boxes for entry and the SIP panel along with the results without needing to scroll the screen. Here is a screen shot of the main form.
Now with the controls in place on the form, I can implement the view. The form creates a new presenter and passed into it a new model during construction. When the calculate menu option is clicked the main form raises the data changed event then calls the OnCalculateMethod on the presenter. When the presenter binds the model to the view, during the set of the points value, the notification is shown to the user via the ShowNotification method.
namespace WWPC.Calc{ public partial class WWPCalculator : Form, IFoodCalcView { private readonly FoodPresenter _Presenter; private NotificationWithSoftKeys _Notification; public WWPCalculator() { InitializeComponent(); _Presenter = new FoodPresenter(this,new FoodModel()); } public int Calories { get { return (string.IsNullOrEmpty(txtCalories.Text)) ? 0 : Int32.Parse(txtCalories.Text); } } public int Fiber { get { return (cmbFiber.Text == "4 or more") ? 4 : (string.IsNullOrEmpty(cmbFiber.Text)) ? 0 :Int32.Parse(cmbFiber.Text); } } public float Fat { get { return (string.IsNullOrEmpty(txtFat.Text)) ? 0 : float.Parse(txtFat.Text); } } public int Points { set { ShowPointsNotification(value); } } public event EventHandler DataChanged; private void mnuExit_Click(object sender, EventArgs e) { this.Close(); } private void mnuCalculate_Click(object sender, EventArgs e) { if (DataChanged != null) this.DataChanged(sender, e); _Presenter.OnCalculatePoints(); } private void mnuClear_Click(object sender, EventArgs e) { txtCalories.Text = string.Empty; txtFat.Text = string.Empty; cmbFiber.Text = "0"; } private void ShowPointsNotification(int points) { _Notification = new NotificationWithSoftKeys { Text = String.Format("Total Points:{0}", points), Caption = "Weight Watchers Point Calculator", RightSoftKey = new NotificationSoftKey(SoftKeyType.Dismiss, "Dismiss"), }; _Notification.RightSoftKeyClick+=new EventHandler(_Notification_RightSoftKeyClick); _Notification.Visible = true; } void _Notification_RightSoftKeyClick(object sender, EventArgs e) { if (_Notification == null) return; _Notification.Visible = false; _Notification = null; } }}
Now, when it is all put together, it looks like so.
Below is a link to the source code. The project was done using Visual Studio 2008 against the windows mobile 5 sdk. It will also work against windows mobile 6 sdk, I just chose version 5 since that is the common sdk. Thanks for reading!!

[Q] DatePickerDialog cancelclick

Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!

[Q]Content Provider - Huge Data

Hi,
Im using a content provider to query data, the following code was working good until I test it in another device(low end) with a larger data(~3000). With a larger data app became unusable, what can I do for improve this?
Code:
public void ContentSearch(String uriS,String id)
{
Uri uri = Uri.parse(uriS);
Cursor cur = getContentResolver().query(uri, NULL,
"_id = " + id, null, null);
cur.moveToFirst();
do {
//Do Things
} while (cur.moveToNext());
cur.close();
}
try to put it in a thread:
Code:
new Thread(new Runnable() {
[user=439709]@override[/user]
public void run() {
//CODE GOES HERE
}
}).start();
You do this for anything that might take the system a long time to execute and isn't directly needed for the UI.
If it is needed by the UI try an AsyncTask:
Code:
AsyncTask<Params,Progress,Result>() {
[user=439709]@override[/user]
protected Result doInBackground(Params params) {
}
protected void onProgressUpdate(Progress progress) {
}
protected void onPostExecute(Result result) {
}
}.execute();
I never used Content Providers so I'm not sure what you would put in for each thing on the Async but here is the Android Docs perhaps you can figure it out
Im filling an array to inflate in listview, my approach is load 25 items then break, and when the list reaches the end load more 25 and so on, but it seems that the cursor is in the same overloaded.
I need it for the UI so I dont have sure if the thread solve the problem, but I will try it anyway.
avlisF said:
Im filling an array to inflate in listview, my approach is load 25 items then break, and when the list reaches the end load more 25 and so on, but it seems that the cursor is in the same overloaded.
I need it for the UI so I dont have sure if the thread solve the problem, but I will try it anyway.
Click to expand...
Click to collapse
You fill the array then you fill the list? This might be what's causing our crash as the list is trying to setup before the array is done.
You could just use the async to do the lookup and set the list item info in the list adapter and as the async finishes each lookup it will enter each item in the list
Sent from my Nexus 7 using XDA Premium HD app

Widget HTTP Request

Hello,
Can anyone help me with code to make widget make an http request and display response in a text view on the widget.
Thanks
Nobody will code YOUR app for free here.
If you have googled and a specific question you can ask here.
EmptinessFiller said:
Nobody will code YOUR app for free here.
If you have googled and a specific question you can ask here.
Click to expand...
Click to collapse
Thank you. I have googled and and just been able to create my first widget. I however need to update the widget with data from a webservice via http request. I have got code to do this in a real app but can't seem to figure it out in a widget. My programming skills is very very low especially for java.
Any help will be appreciated. If I have to pay, how do Ii go about that please.
Thanks
EmptinessFiller said:
Nobody will code YOUR app for free here.
If you have googled and a specific question you can ask here.
Click to expand...
Click to collapse
This is what I came up with but the code won't run unless I take out the whole try/catch block. No errors are shown though.
Code:
public class LovelyBatteryWidget extends AppWidgetProvider {
//remote views object to access visible interface elements
private RemoteViews widgetViews = new RemoteViews("com.yourdomain.battery", R.layout.battery_widget);
/*
* Determine what happens when the widget updates
* - this method is called repeatedly
* - frequency determined by updatePeriodMillis in res/xml widget info file
*/
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
//register for the receiver when the battery changes
Intent received = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
//find out what action has been received
String receivedAction = received.getAction();
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String carrierName = manager.getNetworkOperatorName();
//String msisdn=manager.getSimSerialNumber();
//only carry out amendments if the action is a change in the battery level
if (receivedAction.equals(Intent.ACTION_BATTERY_CHANGED))
{
//get the level amount, pass default value
int level = received.getIntExtra("level", 0);
//indicate the level amount within the text view
this.widgetViews.setTextViewText(R.id.text_level, level+"%"+carrierName);
this.widgetViews.setTextViewText(R.id.text_balance, "4.44");
//this.widgetViews.setTextViewText(R.id.text_data, "1433");
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("myURLGoesHere"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
int text=responseString.length();
this.widgetViews.setTextViewText(R.id.text_data, String.valueOf(text));
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
return;
}
//get component to update
ComponentName appComponent = new ComponentName(context, LovelyBatteryWidget.class);
//update the widget
AppWidgetManager.getInstance(context).updateAppWidget(appComponent, this.widgetViews);
}
}
}
Battery level updates normally and so does balance when i comment out the whole http request part. However, all code including battery level and balance parts won't run when the http request part is included.
You should not try performing any IO operations on main (UI) thread.
I would build service with its own Looper object or using AsyncTask to perform HTTP request and sending back received data.
There is a guide on the internet, i think on android dev docs to make a word of the day widget that gets the word from wiktionary
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods (but only for the first time ;D)
---------------------------------
Gesendet von Tapatalk
---------- Post added at 09:41 AM ---------- Previous post was at 09:40 AM ----------
About the try catch block: with http response you need to cover IOException and TimeoutException and also a few more
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods (but only for the first time ;D)
---------------------------------
Gesendet von Tapatalk

Categories

Resources