i make this code in single application working, but if join with other application , show this dialog "android os network on main thread exception"
package com.kelompok2.bissmilahpulsa;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class coba extends Activity {
EditText nm,nmr;
RadioGroup prov,nom,pem;
TextView error;
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mulaitransaksi);
nm=(EditText)findViewById(R.id.et_nama);
nmr=(EditText)findViewById(R.id.et_nomor);
prov=(RadioGroup)findViewById(R.id.provider);
nom=(RadioGroup)findViewById(R.id.nominal);
error=(TextView)findViewById(R.id.error);
pem=(RadioGroup)findViewById(R.id.pembayaran);
ok=(Button)findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String type=null;
String type1=null;
String type2=null;
switch (prov.getCheckedRadioButtonId())
{
case R.id.rb_as:
type="As";
break;
case R.id.rb_axis:
type="Axis";
break;
case R.id.rb_im3:
type="Im3";
break;
case R.id.rb_telkomsel:
type="Telokmsel";
break;
case R.id.rb_xl:
type="Xl";
break;
}
switch (nom.getCheckedRadioButtonId())
{
case R.id.rb_5:
type1="5";
break;
case R.id.rb_10:
type1="10";
break;
case R.id.rb_20:
type1="20";
break;
case R.id.rb_50:
type1="50";
break;
}
switch (pem.getCheckedRadioButtonId())
{
case R.id.rb_cash:
type2="Cash";
break;
case R.id.rb_hutang:
type2="Hutang";
break;
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("nama", nm.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor", nmr.getText().toString()));
postParameters.add(new BasicNameValuePair("provider", type));
postParameters.add(new BasicNameValuePair("nominal", type1));
postParameters.add(new BasicNameValuePair("jenis_pembayaran", type2));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://appmob.pusku.com/save.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Data Tersimpan");
else error.setText("Data Tersimpan Ke server");
}
catch (Exception e) {
error.setText(e.toString());
}
String nama1 = nm.getText().toString();
String nama2 = nmr.getText().toString();
String nama3 = type;
String nama4 = type1;
String nama5 = type2;
String sms = nama1+"#"+nama2+"#"+nama3+"#"+nama4+"#"+nama5;
Intent i = new Intent (Intent.ACTION_SENDTO,Uri.parse("sms:5556"));
i.putExtra("sms_body", sms);
startActivity(i);
nm.setText(null);
nmr.setText(null);
}
});
}
}
in permission i active that <uses-permission android:name="android.permission.INTERNET"/>
and still not working
You need to run internet activities on a thread separate from main (UI) thread, you can do that by wrapping your code in the following block:
new Thread() {
#Override
public void run() {
//your code here
}
}.start();
Execute your Network related operation in AsyncTask
You can also refer here Android AsyncTask
public class ExcuteNetworkOperation extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
/**
* show dialog
*/
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
/**
* Do network related stuff
* return string response.
*/
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
/**
* update ui thread and remove dialog
*/
super.onPostExecute(result);
}
}
first method
you can create an AsynTask .. Your code should run in background in order to be responsive.. otherwise it will show Not Responding ..
Second Method
You can create a seperate thread for it .. using multitasking.
Third
Right the code in the onCreate after setContentView
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
While all of the answers posted in this thread is correct, asynctasks are not really considering to be a good tool to user for network transactions anymore. The main reasons for this is that the asynctasks are very closely tied to activities so alot issues arise like..."what happens if the activity is destroyed before the network call returns?".
If you really want to implement android best practices (and not to mention impress your fellow Android devs) then why not perform a network task in a service?
I would suggest looking at the Path FOSS project android-prioriy-queue. They make it ridiculously easy to perform task in a service.
Related
i am trying out below code everything works fine when net is connected
here is the workflow
there is a main activity from where on button click this activity should open
it would do the parsing part and then go to next list activity.in case there is a back press or this activity is closed the asynctask should stop using
loader.cancel(true);
this would work perfectly if net is available and tested the issue happens when dont have internet connection
the alert box shows and it goes to the first activity then it crashes
i want the alert box to show and app should not crash and go back to first -->mainactivity
i have refereed this
http://techiedreams.com/android-simple-rss-reader/
How to end AsyncTask onBackPress()
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import com.parser.DOMParser;
import com.parser.RSSFeed;
public class SplashActivity extends Activity {
//private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;
private AsyncLoadXMLFeed loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
String name = i.getStringExtra("name");
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
//new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
String name = i.getStringExtra("name");
//feed = myParser.parseXml(RSSFEEDURL);
feed = myParser.parseXml("http://"+name+".blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
My guess it crashes with NullPointerException.
It is because if you don't have network connectivity you don't create AsyncLoadXMLFeed instance.
So when onDestroy() happened and you call loader.cancel(true); it throws this Exception.
finally did this
thanks anatol needed to check loader != null
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
if(loader != null && loader.getStatus() != AsyncTask.Status.FINISHED) {
loader.cancel(true);
}
//loader.cancel(true);
}
The best and simplest solution for handle this issue is that use try catch block in your onPost execute() in async task. like this
#Override
protected void onPostExecute(String s) {
try {
super.onPostExecute(s);
loading.dismiss();
}catch (Exception ex){
Toast.makeText(UserLogin.this, "Something is going wrong, please try again!", Toast.LENGTH_LONG).show();
}
}
simply this will prevent your app from crash.
I am using the following code to make the android device a ftp server (Android Internal storage). I am getting the exception of os.android.NetworkOnMainThread. I have tried to put the onStart code in the AsyncTask but app never executes and crashes on launch. Any help regarding the ftp server on Android will be great as i have no idea how to get it working.
Here is the MainActivity Code
package com.googlecode.simpleftp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class FTPServer extends Activity {
private static int COMMAND_PORT = 2121;
static final int DIALOG_ALERT_ID = 0;
private static ExecutorService executor = Executors.newCachedThreadPool();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
System.out.println("New game button is pressed!");
//newGame();
return true;
case R.id.quit:
System.out.println("Quit button is pressed!");
showDialog(DIALOG_ALERT_ID);
return true;
default:
return super.onOptionsItemSelected(item); }
}
#Override
protected Dialog onCreateDialog(int id){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id){
FTPServer.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
HEre is the ServerPI Code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerPI implements Runnable{
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
private String baseDir;
private String relativeDir;
private String absoluteDir;
private String fileName;
private String filePath;
public ServerPI(Socket incoming) throws IOException{
this.clientSocket = incoming;
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
out = new PrintWriter(this.clientSocket.getOutputStream(), true);
baseDir = new File("").getAbsolutePath();
relativeDir = "/";
absoluteDir = baseDir + relativeDir;
fileName = "";
filePath = absoluteDir + "/" + fileName;
}
private void readCommandLoop() throws IOException {
String line = null;
reply(220, "Welcome to the SimpleFTP server!");
while((line = in.readLine()) != null){
int replyCode = executeCommand(line.trim());
if(replyCode == 221){
return;
}
}
}
private int executeCommand(String trim) {
// TODO Auto-generated method stub
return 0;
}
public int reply(int statusCode, String statusMessage){
out.println(statusCode + " " + statusMessage);
return statusCode;
}
#Override
public void run(){
try{
this.readCommandLoop();
} catch (IOException e){
e.printStackTrace();
}
finally {
try {
if(in != null){
in.close();
in = null;
}
if(out != null){
out.close();
out = null;
}
if (clientSocket != null){
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
I have put the code in the AsyncTask, here it is
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
ServerSocket s = null;
Socket incoming = null;
try{
s = new ServerSocket(COMMAND_PORT);
String ip = (s.getInetAddress()).getHostAddress();
Context context = this.getApplicationContext();
CharSequence text = ip;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
Thread.sleep(1000);
toast.show();
while(true){
incoming = s.accept();
executor.execute(new ServerPI(incoming));
}
}
catch(Exception e){
System.out.println(e.toString());
e.printStackTrace();
}
finally{
try
{
if(incoming != null)incoming.close();
}
catch(IOException ignore)
{
//ignore
}
try
{
if (s!= null)
{
s.close();
}
}
catch(IOException ignore)
{
//ignore
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Iam calling the longOpertation in onCreate method. What is the problem that the app crashes on launch.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
new LongOperation().execute();
}
Maybe because you didn't set up the permissions in the manifest? You've to set permission for internet usage.
If this doesn't work, please tell us which line is it throwing the exception.
while(true){ incoming = s.accept(); ...} You cannot put that in OnStart(). That should be done in a thread. So ServerSocket s = null; should be a variable of you activity.
So I went with Swiftp application (open source) as a service in my application which helped me to achieve my task. Thanks everyone who stepped forward to help. Here is the link if someone wants to follow
Please post your code here.
NetworkOnMainthreadException occurs because you maybe running Network related operation on the Main UI Thread. You should use asynctask for this purpose
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
//call webservice
//return result here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
http://developer.android.com/reference/android/os/AsyncTask.html. Check the topic under the heading The 4 Steps.
A working example of asynctask # To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?.
The above makes a webserive call in doInBakckground(). Returns result and updates the ui by setting the result in textview in onPostExecute().
You can not do network operation in main thread in android 3.0 higher. Use AsyncTask for this network operation. See this for further explanation
I want to display a progressdialog when a client sends request to the server..the request should be done in background...but i am getting a force close when i use the AsyncTask..Please help ..Thank you
package com.example.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static ProgressDialog Dialog;
String s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// sendreq();
new SendUserTask().execute();
}
});
}
public String sendreq() {
try {
// TODO Auto-generated method stub
SocketAddress sockaddr = new InetSocketAddress("192.168.7.116",
9011);
Socket serversocket = new Socket();
serversocket.connect(sockaddr, 10000);
serversocket.setSoTimeout(10000);
DataOutputStream out = new DataOutputStream(
serversocket.getOutputStream());
out.flush();
DataInputStream in = new DataInputStream(
serversocket.getInputStream());
out.flush();
String msg = "";
msg = "hi";
out.writeBytes(msg);
out.flush();
byte[] message = new byte[100];
in.read(message);
s1 = new String(message);
Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG)
.show();
((TextView) findViewById(R.id.textView1)).setText(s1);
in.close();
out.close();
serversocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
return null;
}
private class SendUserTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Dialog = ProgressDialog.show(MainActivity.this, "",
"Logging In....", true);
super.onPreExecute();
}
protected void onPostExecute(String s) {
if (Dialog.isShowing())
Dialog.dismiss();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
return sendreq();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
this ((TextView) findViewById(R.id.textView1)).setText(s1); is executed from the background thread. you cannot access UI elements outside the UI thread.
You need to move that part to either onProgressUpdate or onPostExecute, or to run it in a runOnUiThread Runnable.
doInBackgorund() is a non-UI thread and you cannot access UI elements inside it. The code inside doInBackground() runs on a separate non-ui thread which does not have access to the UI elements defined in your layout. Also, since you are calling another Activity via intents, you should always keep in mind that an Activity runs on the UI thread and hence you should never start another Activity from inside a non-ui thread.
So, remove the code " ((TextView) findViewById(R.id.textView1)).setText(s1); " accessing the UI elements from inside of doInBackground() and instead put it inside onPostExecute(), which is a UI thread and is called after doInBackground() finishes the background processing.
Ok.... After googling a lot i finally came to understand that you cant access UI elements from main thread into a new non-UI thread....So you cant use elements like textview or even getApplicationContext mtd tht v use for toast in the dobackground mtd or even in anyother mts that the dobackground is calling....This also applies for the new Thread() using runnable..Thank you njzk2 for your help :)
i got a class i made, that makes a simple GET request and displays toast messege with the response...
if i call the function from a bottom event click it displays the messege with the data returned, just ok.
but if i call the same function from a brodcast reciver class, it just showing the massege with the data '' (null)
i belive that it showing the massege before i could get the data, and with the button it waits for the data..
how can i make it work from the brodcast reciver?
the class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class myclass{
public static void doHttpRequest(String param1, Context context){
String ret="";
try {
URL url = new URL("http://website.com/page?param="+param1);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ret=readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
CharSequence text = "return data- "+ret;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
String line = "";
String alllines = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
alllines=alllines+line;
}
return alllines;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return alllines;
}
}
from the button it works fine:
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myclass.doHttpRequest("blabla", getBaseContext());
}});
from the brodcast reciver witch in different class it won't return data, but shows the toast..
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
myclass.doHttpRequest("blabla", context);
break;
} }
}
please HELP.... :) THANKS
All fixed.. it's seems to be a project settings error, or premmisions error (but i had the premissions in the manifest... must not apply in the apk while compiling)
i copied the classes to enother project made by erlier version of eclipse, and it's works there like a charm...
thanks anyway..
i tried for hours to fix it in the code.. and it was the settings....
I created a myclass.java and CustomBroadcastReceiver.java and tried your code by removing the break statement and one extra curly brace from the CustomBroadcastReceiver.java class and it worked fine for me.
The following code in Activity class demonstrates registering, uninteresting receiver and a Handler for a sample/test broadcast.
CustomBroadcastReceiver customBroadcastReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customBroadcastReceiver = new CustomBroadcastReceiver();
registerReceiver(cusoBroadcastReceiver, new IntentFilter("com.example.app.testbroadcast"));
// For test broadcast only.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
sendBroadcast(new Intent("com.example.app.testbroadcast"));
}
}, 2000);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(customBroadcastReceiver);
}
Hope this helps.
I'm making a Cloud Service that uses a standard HTTP get to get commands. I use a service (extending class IntentService as opposed to Service) to keep things in sync. I have the checking going on in a TimerTask firing off every 3 seconds. The problem is that when the user goes back to the activity to turn it off if they want, they press a toggle button. How do I tell the TimerTask (or the IntentService running a timer task) to stop and start it?
The service itself is getting destroyed after it handles the intent and creates the task, so would a Service be more appropriate for this than an IntentService? Even if thats the case, the question about stopping and starting the TimerTask remains.
Here's the code to the intentservice:
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.widget.*;
public class syncservice extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public syncservice() {
super("syncservice");
}
public static final String PREFS_NAME = "prefcs";
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String uid = intent.getExtras().get("uid").toString();
final String dvname = intent.getExtras().get("dvname").toString();
final long period = intent.getExtras().getLong("period");
final Context ctx = getApplicationContext();
final Toast toast = Toast.makeText(ctx,"An error occured with the service. It will automatically turn off.", 0);
final Handler handler = new Handler();
TimerTask timertask = new TimerTask () {
#Override
public void run() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("doservice", false)) {
String command = netread("url here");
//TODO Parse command from Pulling
if (command.contains("<")) {
//TODO what to do if an error occurred (exceptions already caught
Runnable showerrormessage = new Runnable() {
public void run() {
toast.makeText(ctx,"new text",0);
toast.show();
}
};
handler.post(showerrormessage);
}
}
}
};
Timer timer = new Timer();
timer.schedule(timertask,0,period);
return super.onStartCommand(intent,flags,startId);
}
public void onDestroy() {
Toast.makeText(getApplicationContext(), "The Service has died", Toast.LENGTH_SHORT).show();
return;
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "Intent Handled", 0).show();
}
public final String netread(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
} catch (ClientProtocolException e) {
//Toast.makeText(getApplicationContext(),"Client Protocol Exception! Try again.",0).show();
return "<";
} catch (IOException e) {
//Toast.makeText(getApplicationContext(),"IO Exception! Make sure you are connected to the internet and try again.", 0).show();
return "<";
}
}
}
Thanks a bunch for helping me out!
For what you're trying to do, Handler may be more useful. That link BTW shows also how to stop it from the UI.