trying to stop execution for 2 seconds - java

I have a button and when clicked calls a method which starts a thread. but there is stop for that thread, fine. I want that to complete the thread first then to execute the rest of the code.
I tried to use wait() but not working.
public void configure(Button arg0,TextView arg1) throws InterruptedException{
//calling OpenDeviceListener
readText=arg1;
button= arg0;
//handler
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("Handler","running");
if (actualNumBytes != 0x00) {
Log.d("handler","if");
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Log.d("handler","if 312");
actualNumBytes = 0;
Log.d("handler","if end");
}
Log.d("handler","closed");
}
};
Log.d("163","tab");
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
Log.d("167","tab");
act_string = getIntent().getAction();
if(-1 != act_string.indexOf("android.intent.action.MAIN"))
{
Log.d(TAG, "android.intent.action.MAIN 171");
}
else if(-1 != act_string.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
{
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED 175");
}
if(!uartInterface.UsbFeatureSupported())
{
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT).show();
Log.d("182","tab");
readText.setText("No Support USB host API");
Log.d("184","tab");
uartInterface = null;
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if(READ_ENABLE == false) {
READ_ENABLE = true;
Log.d("192","tab");
handlerThread = new readThread(handler);
handlerThread.start();
}
Log.d("192","End");
try{
this.wait(100);
}
catch(InterruptedException e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
// TODO Auto-generated method stub
Log.d("205","OpenDeviceListener");
boolean flags;
if(false == isConfiged) {
Log.d("209","OpenDeviceListener");
Toast.makeText(global_context,""+((Boolean)uartInterface.isConnected()), Toast.LENGTH_LONG).show();
isConfiged = true;
// writeButton.setEnabled(true);
if(uartInterface.isConnected()) {
Toast.makeText(global_context,""+(Boolean)uartInterface.isConnected(), Toast.LENGTH_SHORT).show();
Log.d("213","OpenDeviceListener");
flags = uartInterface.UartInit();
if(!flags) {
Log.d(TAG, "Init Uart Error 2");
Toast.makeText(global_context, "Init Uart Error", Toast.LENGTH_SHORT).show();
} else {
if(uartInterface.SetConfig(baudRate, dataBit, stopBit, parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
}
}
and plz clear one thing the stop() is not called for the thread, up to when the thread will run.
Thanks

final Runnable runnable = new Runnable() {
#Override
public void run() {
//this method will be called after 2 seconds
//do your task here
}
};
final Handler h = new Handler();
h.removeCallbacks(runnable); // cancel the running action (the
// hiding process)
h.postDelayed(runnable, 2000);

try this:
Object lock = new Object;
synchronized(lock){
lock.wait();
}
this will block current Thread running these code.
when it's time notify the blocked code
synchronized (lock) {
lock.notify();
}
if just want to sleep the thread for a specific time why not use
Thread.sleep(1000);

Related

Service Socket Disconnect on Background->Foreground switch

I am writing an IRC Client. The socket connection to the IRC Server is handled via a service. I have managed to stabilize all the UI elements of the Activities in question during the orientation change, but somehow the socket that is maintained by the service is being closed during the change.
Here is what I believe to be the relevant code. Please let me know if you need to see more.
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
#Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
if (line.toUpperCase().startsWith("PING ")) {
SendMessage("PONG " + line.substring(5));
}
else
queueMessage(line);
}
}
catch (Exception e) {}
}
});
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return myBind;
}
#Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
#Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
if(server.PASS != "")
SendMessage("PASS " + server.PASS);
//write nickname
SendMessage("NICK " + server.NICK);
//write username login
SendMessage("USER " + server.NICK + " 0 * :Fluffy IRC");
String line;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
//change to alt Nick
if(!server.NICK.equals(server.ALT_NICK) && !server.ALT_NICK.equals(""))
{
server.NICK = server.ALT_NICK;
SendMessage("NICK " + server.NICK);
}
else
{
queueMessage("Nickname already in use");
socket.close();
return false;
}
}
else if (line.toUpperCase().startsWith("PING ")) {
SendMessage("PONG " + line.substring(5));
}
else
{
queueMessage(line);
}
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
conn = null;
}
};
#Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
unbindService(mConnection);
}
#Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
#Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
#Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Im not entirely certain what I am doing wrong there. Obviously there's something I'm missing, haven't found yet, or haven't even thought to check. What happens though is that after the orientation change my Send command gives me this message and nothing happens:
06-04 22:02:27.637: W/System.err(1024): java.net.SocketException: Socket closed
06-04 22:02:27.982: W/System.err(1024): at com.fluffyirc.ConnectionService.SendMessage(ConnectionService.java:90)
I have no idea when the socket is getting closed, or why.
Update
I have changed the code so that rather than binding to the service and using that to start it, instead I call startService and stopService at appropriate points as well as binding to it, on the thought that the service was being destroyed when the binding was lost. This is working exactly like it was before I changed it. The socket still closes on an orientation change, and I have no idea why.
Update :- Code and description
I added the code changes recently made for Start/Stop service and START_STICKY. I also recently read a very good article explaining how the orientation change process flow works and why its NOT a bad idea to add the android:configChanges="orientation|screenSize" line to your manifest. So this fixed the orientation issue, but its still doing the same thing if I put the activity into background mode, and then bring it back to the foreground. That still follows the same Save/Destroy/Create process that the orientation does without that manifest line...and it still closes my socket, and I still don't know why.
I do know that it doesn't close the socket until the re-create process...I know this because the message queue will display messages that were received while the app was in the background, but once I bring it back forward it closes the socket and nothing else can be sent or received.
'Socket closed' means that you closed the socket and then continued to use it. It isn't a 'disconnect'.
You need to put something into that catch block. Never just ignore an exception. You might get a surprise when you see what the exception actually was.
NB Socket.isConnected() doesn't tell you anything about the state of the connection: only whether you have ever connected the Socket. You have, so it returns true.

Android bug in thread

I'm working on an android Quiz app with connection to a server over a socket. On the client side (Android device) I check in a while loop the answers which are given by a server (Java server). The connection and the receiving of the answer all goes good. The problem is that in my class to check for answers there's a bug. To give more information I will include a part of the code here:
public void startClient(){
checkValue = new Thread(new Runnable(){
#Override
public void run() {
try
{
final int PORT = 4444;
final String HOST = "192.168.1.118";
Socket SOCK = new Socket(HOST, PORT);
Log.e("success", "You connected to: " + HOST);
quizClient = new QuizClient(SOCK);
//Send the groupname to the list
PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
OUT.println(groupName);
OUT.flush();
Thread X = new Thread(quizClient);
X.start();
connected = true;
}
catch(Exception X)
{
Log.e("connection error", "Error: ", X);
}
}
});
checkValue.start();
}
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
Message msg = new Message();
String textTochange = buffer;
msg.obj = textTochange;
mHandler.sendMessage(msg);
Thread.sleep(3000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
//String[] myStringArray = new String[];
value.clear();
String[] items = text.split(";");
for (String item : items)
{
value.add(item);
Log.e("message", item);
//System.out.println("item = " + item);
}
if(value.get(0).equals("1")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
rad1.setText(value.get(3));
rad2.setText(value.get(4));
rad3.setText(value.get(5));
rad4.setText(value.get(6));
questionGroup.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else if (value.get(0).equals("2")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
answer.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else
{
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText(text);
}
}
};
#Override
protected void onStop()
{
if (connected == true){
try {
quizClient.DISCONNECT();
} catch (IOException e) {
e.printStackTrace();
}
}
if(checkValue != null)
{
checkValue.interrupt();
}
super.onStop();
closeApplication();
}
So I make a new instance of this class (where I actually check the incoming stream of data)
public class QuizClient implements Runnable {
//Globals
Socket SOCK;
Scanner INPUT;
Scanner SEND = new Scanner(System.in);
PrintWriter OUT;
public QuizClient(Socket X)
{
this.SOCK = X;
}
public void run()
{
try
{
try
{
INPUT = new Scanner(SOCK.getInputStream());
OUT = new PrintWriter(SOCK.getOutputStream());
OUT.flush();
CheckStream();
}
finally
{
SOCK.close();
}
}
catch(Exception X)
{
Log.e("error", "error: ", X);
}
}
public void DISCONNECT() throws IOException
{
OUT.println("DISCONNECT");
OUT.flush();
SOCK.close();
}
public void CheckStream()
{
while(true)
{
RECEIVE();
}
}
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Log.e("test", MESSAGE);
}
}
}
public void SEND(String X)
{
OUT.println(X);
OUT.flush();
}
}
So the bug persist I think in the following class:
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
What I do here is make a thread and check if the "message" is not equals at null. The message come from the other class:
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Now most of the time this works good but there are 2 problems. When I go out of the page it disconnect from the server (works) I go back on the page and connect again to the server but this time I don't get any values on the screen (receiving is okj but for one of the other reason it does not go good in my handler). Also get an indexoutofboundexception after a time:
question.setText(value.get(2));
A second problem occurs some time while the program runs. There are moments that I also don't get a value on my interface while it correctly receive the input.
So my guess is that my solution of the thread to read in the values is not the best way to handle it. So now I ask to people with more experience what I can do to make this work without major problems? You need to know the connection works and I get the value in my QuizClient class. So the problem need to be in my main class.
My oncreate class:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
selectgroep = (Spinner) findViewById(R.id.groepen);
questionGroup = (RadioGroup) findViewById(R.id.QuestionGroup);
sendAnswer = (Button) findViewById(R.id.sendAnswer);
rad1 = (RadioButton) findViewById(R.id.radio0);
rad2 = (RadioButton) findViewById(R.id.radio1);
rad3 = (RadioButton) findViewById(R.id.radio2);
rad4 = (RadioButton) findViewById(R.id.radio3);
answer = (EditText) findViewById(R.id.textanswer);
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
try {
connect();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Code na het drukken op de knop
startserver = (Button) findViewById(R.id.startserver);
startserver.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startClient();
getID();
testvalue();
}
});
sendAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Stuur antwoord door en sluit alles af
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
answer.setText("");
rad1.setChecked(true);
rad1.setText("");
rad2.setText("");
rad3.setText("");
rad4.setText("");
question.setText("Wachten op server ... ");
}
});
}
Thank you in advance,
Thomas Thooft

Android Runnable Slowing down my device

I'm trying to develop an app which gets some data from an HTML webpage and displays it every second.
For that i'm using a runnable in this way:
In the OnCreate() method:
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
And then this other method:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
rowTextView.setText(returned);
} catch (Exception e) {
e.printStackTrace();
}
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(this, 500);
}
};
The problem is that if i press the back button, for example, the app starts to behave slowly and until i don't force close the whole app the device runs too slow!
Thank you!
EDIT
This is the whole class:
public class HttpExample extends Title {
GetMethodEx test, moredata ;
String returned;
TextView rowTextView, rowTextView2;
LinearLayout ll;
private Handler mHandler = new Handler();
String newString;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
rowTextView = (TextView)findViewById(R.id.textView2);
rowTextView2 = (TextView)findViewById(R.id.textView1);
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
Bundle extras = getIntent().getExtras();
newString = extras.getString("STRING_I_NEED");
test = new GetMethodEx();
moredata = new GetMethodEx();
try {
String name = moredata.GetName(newString);
rowTextView2.setText(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
}
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
}
Your program slows down because you are running the thread on the GUI thread. That isn't recommended. However, I notice you are setting text after you are done. Here's a few things you could do.
Run the sensor data gathering in a different thread. Update the text by the runOnUiThread command.
Use an AsyncTask, this seems to be an ideal situation for one.
For such a regular occurrence, that doesn't require a UI thread, I would suggest using a ScheduledExecutorService.
The simplest to start with would be the first, but I would look carefully at the second option. The first option would be something like this: (Note, you will need to replace MainActivity with the name of your activity)
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
You can attach you Handler to work on a different thread by using HandlerThread. For example:
HandlerThread ht = new HandlerThread("nonUiThread");
ht.start();
Handler mHandler = new Handler(ht.getLooper());
but more preferably, I would suggest you to use AsyncTask in your case.
Got it to work with this:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
HttpExample.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
rowTextView.setText(returned.get(0)+returned.get(1));
rowTextView2.setText(returned.get(2));
}
});
}
};

Downloading and installing APK

I made code that download APK from ftp, and I`m trying to install it after download. I wrote this for Honeycomb, so in every connection i have to use threads. How can I use startActivity in class within thread, or wait for thread to finish?
public class FTPapkDowload {
protected static final String TAG = "Tablet Development";
public FTPClient mFTPClient = null;
public FTPClient mFtp = null;
public void Start() {
Thread apkdowload = new Thread(new Runnable() {
#Override
public void run() {
ftpConnect("mysite", "username", "password",21);
Log.d(TAG, "Connected");
ftpDownload("/httpdocs/Shamir/app.apk", "sdcard/Download/app.apk");
ftpDisconnect();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Download/" + "app.apk")), "application/vnd.android.package-archive");
startActivity(intent); //Here is the problem
}
//Connection
public boolean ftpConnect(String host, String username,
String password, int port) {
try {
mFTPClient = new FTPClient();
mFTPClient.connect(host, port);
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
Log.d(TAG, "Error: could not connect to host " + host);
}
return false;
}
//Downloading
public boolean ftpDownload(String srcFilePath, String desFilePath) {
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(
desFilePath);
status = mFTPClient
.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
Log.d(TAG, "Disconected from FTP on apk Download");
return true;
} catch (Exception e) {
Log.d(TAG,"Error occurred while disconnecting from ftp server on apk download.");
}
return false;
}
});
apkdowload.start();
}
}
You can use a handler:
private Handler handler = new Handler(){
public void handleMessage(Message msg)
{
}
};
When your thread is done running the code it needs to call: handler.sendEmptyMessage(0);
More info: http://developer.android.com/reference/android/os/Handler.html
The cleanest way to do this is for your FTP download code to notify your main thread that it has finished, and make the main (UI) thread call startActivity. You can do this using any number of methods for communication between threads, for example a Handler:
http://developer.android.com/reference/android/os/Handler.html
Or simply Activity.runOnUiThread:
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
A good read is the "Painless Threading" blog post:
http://android-developers.blogspot.com/2009/05/painless-threading.html
I guess you need to pass context of your activity to the class in which you want to use activity's methods.
To execute UI methods you have run this on UI Thread:
Put this inside your normal Threads run() Method:
YourClass.this.runOnUiThread(new Runnable() {
#Override
public void run() {
startyourActivity();
}
});

How to create a boolean method to return value from handler

I have created a class to check access of internet on device, my class code is
public class CheckInternet {
private static Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
status = false;
System.out.println("Status False");
} else { // code if connected
status = true;
System.out.println("Status True");
}
}
};
private static void isNetworkAvailable(final Handler handler, final int timeout) {
new Thread() {
private boolean responded = false;
#Override
public void run() {
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
} catch (Exception e) {}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0);
}
else { handler.sendEmptyMessage(1);
}
}
}
}.start();
}
}
I want to create a public static boolean method which returns me the status, I have come up with some code
private static Boolean status = true ;
public static Boolean isConnected() {
Runnable runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
isNetworkAvailable(h,2000);
}
};
runnable.run();
return status;
}
But the issue is that it always returns me the old status value, as while the time the thread is running, the method send me the old status value.
I want to get the updated status value.
You better use
isReachable(timeout)
http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28java.net.NetworkInterface,%20int,%20int%29
Regards

Categories