I'm trying to connect to a PC server (using Hercules) through TCP from an android app (client) but I'm really lost and don't know where to go. None of the tutorials are fully working for me, most of them can allow me to send messages from client to server but not vice versa.
I read about connections not supposed to be run from the "main thread" but what does that mean?
Also any examples of a TCP connection from android would be great.
Thanks!
I suspect that the "main thread" in this context means that thread that is managing the user interface. If you do anything much in this thread, you run the risk of Android killing your app because it appears to have hung.
Personally, I don't think it's a huge problem to have the user interface thread block for a few milliseconds to do a TCP operation. You'd need to make sure that you code the operation to have sensible timeouts, so you don't end with a dead app because the remote server takes too long to respond.
The official way to handle situations like this is to define the network operations in services, or in separate threads, and have the user interface thread communicate with those services or threads using short-lived operations.
This process is documented with examples here:
https://developer.android.com/training/basics/network-ops/connecting
Main thread in android is responsible to create and display UI on screen
to perform task related to connection strictly need to use background thread otherwise UI become laggy.
There are two method available to perform background Task
Runnable:
new Thread(new Runnable() {
public void run() {
..... // code here
}
}).start();
Android AsyncTask: https://developer.android.com/reference/android/os/AsyncTask
Like #Kevin Boone said, Main thread means UI thread in Android.
You can't do networking operations in the Main thread, otherwise you will get NetworkOnMainThreadException. You can create a new thread and then pass result back to the Main thread using Handler. Code could look like this:
public class MyActivity extends AppCompatActivity implements FetchDataUseCase.Listener {
private FetchDataUseCase fetchDataUseCase;
private TextView textView;
private Button dataButton;
public void onCreate() {
textView = findViewById(R.id.textView);
dataButton = findViewById(R.id.dataButton);
dataButton.setOnClickListener(v -> getDataFromNetwork());
fetchDataUseCase = new FetchDataUseCase(this);
}
void getDataFromNetwork() {
fetchDataUseCase.fetchDataAndNotify();
// start async operation! and receive result in onDataFetched()
}
#Override
public void onDataFetched(String data) {
// now you are in Main thread
// do something with data
textView.setText(data);
textView.setVisibility(View.VISIBLE);
}
#Override
public void onError() {
textView.setText("ERROR!!!");
textView.setVisibility(View.VISIBLE);
}
}
public class FetchDataUseCase {
public interface Listener {
void onDataFetched(String data);
void onError();
}
private final Listener listener;
private final Handler handler = new Handler(Looper.getMainLooper());
public FetchDataUseCase(Listener listener) {
this.listener = listener;
}
public void fetchDataAndNotify() {
new Thread(() -> {
String myData = "";
try {
// your networking operation
// where you receive some data
} catch (Exception e) {
handler.post(() -> listener.onError();
} finally {
// close stream, file, ...
}
// pass it back to Listener in Ui Thread
handler.post(() -> listener.onDataFetched(myData);
}).start();
}
}
read ThreadPoster: Multi-Threading in Android
And don't use AsyncTask =)) Async task is deprecated
Also, you need to add permision to your AndroidManifest file.
<uses-permission android:name="android.permission.INTERNET"/>
Hope it will help you)) Good luck!
Related
I am building an app that requests the temperature of a server. When a button is pressed, I would like the app to:
1) Show a 'contacting server' message and show a spinning progress bar.
2) Contact the server on a new thread.
3) Display the result and hide the progress bar.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
private Button mFetchTempButton;
private TextView mResultTextView;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultTextView = (TextView) findViewById(R.id.result_textview);
mFetchTempButton = (Button) findViewById(R.id.fetch_temperature_button);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mFetchTempButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mResultTextView.setText("Contacting server... ");
mProgressBar.setVisibility(View.VISIBLE);
String[] args = {};
String temperature = RequestServerTemp.main(args);
mProgressBar.setVisibility(View.INVISIBLE);
mResultTextView.setText("Server temperature is " + temperature);
}
});
}
}
This calls the java class 'RequestServerTemp', which uses a Callable to make the server request on a new thread:
public class RequestServerTemp {
public static String main(String[] args) {
final ExecutorService service;
final Future<String> task;
String result = "";
service = Executors.newFixedThreadPool(1);
task = service.submit(new GetTemp());
try {
result = task.get();
}
catch(InterruptedException | ExecutionException ex) {
ex.getMessage();
}
service.shutdownNow();
return result;
}
}
class GetTemp implements Callable<String> {
public String call() {
// simulate a long networking operation
try {
Thread.sleep(3*1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return "30 degrees C";
}
}
The error this causes is that the App only updates once the whole onClick has been completed. This prevents my required step 1) from occurring. I am new to Android, and this raises several questions for me:
1) Why does onClick execute at the end, unlike traditional scripting languages which execute line by line?
2) If I've launched RequestServerTemp in a new Thread, why does MainActivity wait for it to finish? I feel this is bad for an app, and delays like this are the whole reason we launch networking in new threads.
3) Several similar questions to this say that AsyncTask is the 'correct' way to handle networking, rather than Runnable or Thread. Is that true, and should I avoid using Runnable and Thread in an App?
I am mostly interested in question 3, as many stackoverflow answers point to using Runnable and Thread techniques to accomplish networking, and now I am here I am worried I've wasted a lot of time and effort. Thanks for reading, and any general hints and advice for a new app developer (or stackoverflow user!) are welcome.
result = task.get();
get() is a blocking method. It waits until T is available to be returned. That's why "MainActivity wait for it to finish".
Is that true, and should I avoid using Runnable and Thread in an App?
No it is not. When I am not allowed to use third party library to send requests to a webservice, I use an ExecutorService.
Why does onClick execute at the end, unlike traditional scripting
languages which execute line by line?
it does not execute at the end. You are providing a delegate to your mFetchTempButton, the code in the callback, onClick, is executed when the event on click takes place.
you may know about Google Cloud Messaging
The problem is that when a gcm message triggers by the server, my application receives a bundle from google play services, this happen at GcmBroadcastReceiver.java. Here i can send this data to other classes in order to append some info from the server.. well. I got stuck when i try to update, for example, some views in the UI thread.
HOW I CAN DO THIS?
Imagine that MainActivity.java is the UI thread when i declare the views, etc.
I tried to create here a public static method which can be called directly by GcmBroadcastReceiver.java by this way: MainActivity.*updateUI*(args..), but it throws this exception:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Can anyone try to explain me this? i also know about asyncTask but i cant imagine how it works. I also find some pages explaining events that are fired by the UI thread it self like runnables that do some task in background. Im searching something like this:
MainActivity extends Activity{
...
protected void onCreate(Bundle blabla)..{
setContentView(R.layout.blabla);
registerSomeEvent(this);
}
private void handleEvent(Bundle ...){
... do stuff with the data provided in the UI thread
}
}
And here at GcmBroadcastReceiver, when gcm push some data, trigger that magic event in order to perform updates at the UI thread with some views like ListViews or TextView
One way is to use use LocalBroacastManager. For how to implement is, there is a great example on how to use LocalBroadcastManager?.
LocalBroadcast Manager is a helper to register for and send broadcasts of Intents to local objects within your process. The data you are broadcasting won't leave your app, so don't need to worry about leaking private data.`
Your activity can register for this local broadcast. From the GCMBroadcastReceiver, you send a local broadcast when you receive something in GcmBroadcastReceiver. Inside your Activity you can listen to the broadcast. This way if the activity is in the forefront/is active, it will receive the broadcast otherwise it won't. So, whenever you receive that local broadcast, you may do the desired action if activity is open. This is like saying to the activity that "Hey Activity, I've received a message. Do whatever you want with it".
If you want to do for the whole app, then you can make all your activities extend an abstract activity. And inside this abstract activity class you can register it for this 'LocalBroadcast'. Other way is to register for LocalBroadcast inside all your activities (but then you'll have to manage how you'll show the message only once).
You can use Handlers in your MainActivity in order to comunicate with UI Thread.
Communicating with the UI Thread
public class MainActivity extends Activity{
public static final int NEW_DATA_AVAILABLE = 0;
public static final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MainActivity.NEW_DATA_AVAILABLE:
String newData = msg.getData().getString(MyClass.DATA);
//Do some stuff with newData
break;
}
}
};
}
and in your non Activity class
public class MyClass implements Runnable{
Thread thread;
public final static String DATA = "new_data";
public MyClass(){
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
Message msg = mHandler.obtainMessage(MainActivity.NEW_DATA_AVAILABLE);
Bundle bundle = new Bundle();
bundle.putString(DATA, "We have received new data");
msg.setData(bundle);
MainActivity.handler.sendMessage(msg);
}
}
}
I need to update ui from runnable. My logic goes like below.
I start the runnable from onCreate of the fragment lifecycle. And the runnable instance is responsible to request network. The problem is I don`t know how to update the fragment after runnable instance fetched the data from network.
code to start runnable in fragment in CustomFragment.java.
public void onCreate(Bundle savedInstanceState) {
Log.d(DEBUG_TAG, "onCreate");
super.onCreate(savedInstanceState);
accountMgr.requestAccountInfo();
}
code to start runnable in AccountManager.java
/**
* request Account info from server
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void requestAccountInfo() {
Account act = getCurrentAccount();
Thread t = new Thread(new RequestAccountInfoTask(act));
t.start();
}
/**
* automatically update Account info, like space usage, total space size, from background.
*/
class RequestAccountInfoTask implements Runnable {
private Account account;
public RequestAccountInfoTask(Account account) {
this.account = account;
}
#Override
public void run() {
doRequestAccountInfo(account);
}
}
runOnUiThread() requires Activity reference. There are alternatives. You don't need Activity reference to your Thread. You can always get UI handler with the main looper. Pass other arguments like your interface to update the fragment upon completion of your task.
class RequestAccountInfoTask implements Runnable {
private Account account;
private Handler mHandler;
public RequestAccountInfoTask(Account account) {
this.account = account;
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public void run() {
doRequestAccountInfo(account);
//use the handler
}
}
Anything you run on the instantiated Handler will be on UI thread.
Of course, using runOnUiThread() is totally reasonable.
you can use runOnUIThread method of activity.
here's code may be help you:
class RequestAccountInfoTask implements Runnable {
private Account account;
public RequestAccountInfoTask(Account account) {
this.account = account;
}
#Override
public void run() {
doRequestAccountInfo(account);
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// you can update fragment UI at here
}
});
}
}
}
Please take a look at AsyncTask for updating the UI from a thread:
http://developer.android.com/reference/android/os/AsyncTask.html
Here are the highlights from the above link:
Class Overview AsyncTask enables proper and easy use of the UI thread.
This class allows to perform background operations and publish results
on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler
and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the
most.) If you need to keep threads running for long periods of time,
it is highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor, ThreadPoolExecutor and
FutureTask.
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread. An
asynchronous task is defined by 3 generic types, called Params,
Progress and Result, and 4 steps, called onPreExecute, doInBackground,
onProgressUpdate and onPostExecute.
You Cannot Update UI from runnable. You Need Handler for Updating UI. See this for more info.
The UI only can be modified by the thread that create it. In tho most cases is by the UI thread. So you need yo update using runOnUiThread method. Good Luck
I recommend using an AsynTask or you can just try this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "ON UI Thread", Toast.LENGTH_LONG).show();
}
});
I know it's a bit different answer. But I want you to see Android Annotations. Which are very easy to use . I use them only for background and Ui thread. Do every task in background thread by writing #Background over your method name. And do all the UI update in UI thread. I advice you to just check it once. http://androidannotations.org/
Thanks
And as far as your answer is concern . You can not update your UI from runnable. See the asyn task for updating your Ui.
You can use the event bus to do it - http://square.github.io/otto/
It is pretty simple. Just send event from your Thread when you need to update the UI like this:
...
//in the end of your heavy job:
bus.post(new YourEvent());
and in your Activity create method:
#Subscribe
public void onYourEvent(YourEvent event) {
//do what you want there
}
by the way, you can pass any data through event, it is your custom class! Please read manual how to set up this lib, register activity for bus. It is very useful and easy-to-use
You can create a Runnable that then posts to the main thread. From Google's developer pages on Processes and Threads
This implementation is thread-safe: the background operation is done
from a separate thread while the ImageView is always manipulated from
the UI thread.
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// a potentially time consuming task
final Bitmap bitmap =
processBitMap("image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
Is there any way to call an activity from something that doesnt extend Activity? without running it on UI-tread. I want toast-messages in my game, like in candy crush. But I have no idea how to call the toast-activity in an efficient way during real-time.
I know you can use context and get activity from that but it does not run very smoothly. Does anyone have experience with how to do this?
Toasts as well as other components that manipulates the user interface must not be used outside of the UI thread.
What you could do in order to solve your issue, is to design a messaging system between the thread managing you game, and your UI thread. In order to do so, you can use a Handler and its messaging facilities (sendMessage, post, postDelayed ...) to send messages or even Runnables to be run on your main thread.
If you create a Handler in the main thread, it will automatically associate itself with your main thread's event loop, thus making every work sent to it be executed in the main thread.
A basic example of what you could do would be :
class MainActivity extends Activity {
// The handler is associated with your Activity's thread
private Handler _handler = new Handler();
// ...
private Thread _worker = new Thread() {
#Override
public void run() {
_handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Some text", Toast.LENGTH_SHORT).show();
}
});
}
};
};
As a shorthand, you could also use Activity.runOnUiThread(Runnable r) that executes the given runnable in the UI thread by default.
I am having a problem with modifying EditText in another function started by the thread:
Thread thRead = new Thread( new Runnable(){
public void run(){
EditText _txtArea = (EditText) findViewById(R.id.txtArea);
startReading(_txtArea);
}
});
my function is as follows:
public void startReading(EditText _txtArea){
_txtArea.setText("Changed");
}
It always force closes while trying to modify the edittext. Does someone know why?
UI views should not be modified from non-UI thread. The only thread that can touch UI views is the "main" or "UI" thread, the one that calls onCreate(), onStop() and other similar component lifecycle function.
So, whenever your application tries to modify UI Views from non-UI thread, Android throws an early exception to warn you that this is not allowed. That's because UI is not thread-safe, and such an early warning is actually a great feature.
UPDATE:
You can use Activity.runOnUiThread() to update UI. Or use AsyncTask. But since in your case you need to continuously read data from Bluetooth, AsyncTask should not be used.
Here is an example for runOnUiThread():
runOnUiThread(new Runnable() {
#Override
public void run() {
//this will run on UI thread, so its safe to modify UI views.
_txtArea.setText("Changed");
}
});
First of all take a look at your log, it usually contains a stack trace when an app shuts down.
You shouldn't run the thread like you normally do, instead use runOnUiThread:
Runnable thRead = new Runnable(){
public void run() {
EditText _txtArea = (EditText) findViewById(R.id.txtArea);
startReading(_txtArea);
}
};
runOnUiThread(thRead);
The explaination: Only the UI thread is allowed to change the state of UI components.
This article may help you.
http://android-developers.blogspot.com/2009/05/painless-threading.html
There are few options:
1. run it on UI thread Activity.runOnUiThread(Runnable)
2. use AsyncTask
Except runOnUiThread() (which works), there is also another way, which I know of:
Define a handler in your UI (Activity) class:
public class MainActivity extends Activity {
.....
Handler uiThreadHandler = new Handler() {
public void handleMessage(Message msg) {
Object o = msg.obj;
if (o==null) o = "";
TextView textIn = (TextView)findViewById(R.id.textin);
textIn.setText(o.toString());
}
};
}
and from inside some thread you can call it:
Message msg = uiThreadHandler.obtainMessage();
msg.obj = "Text for EditView";
uiThreadHandler.sendMessage(msg);
By default, the main thread is the UI thread. All code that modifies the appearance of the application needs to be run in this thread. If you want to have multiple threads in your application that can modify the UI I would suggest using the AsyncTask class.
public someMethod(){
new ChangeTextTask().execute();
}
private class ChangeTextTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
startReading(_txtArea);
return null;
}
}
However, you need to take steps to prevent multiple threads from accessing the EditText object at once. Otherwise you'll wind up getting a CurrentModificationException error.
http://developer.android.com/reference/android/os/AsyncTask.html