I have followed this tutorial to launch a url on android through jni call. It runs successfully.
In the same way I want to display a toast message from my cocos2dx layer like this:
public static void openURL(String url) {
Toast.makeText(me,url,Toast.LENGTH_LONG).show();
}
But its crashing with error: Can't create handler with thread. Do you know how can I display it correctly?
Try below code this will definately work for you.
First Create one Runnable interface in your class file like this,
Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Your url string...",Toast.LENGTH_SHORT).show();
}};
Then create one Handler object and call that runnable interface like below,
Create Handler object like,
Handler handler;
initialize it like,
onCreate(){
.................
handler = new Handler();
.................
}
then call runnable whenever you want like,
handler.post(runnable);
You can't run UI stuffs on a background thread.
You should use an AsyncTask and put that code in the on pre/post execute or if your just displaying a toast you can run it on the UI thread
runOnUiThread(new Runnable() {
}
So this was from 2012.
I guess not a lot people use cocos2d-x.
Ok this how you do this on cocos2d-x.
Edit the AppActivity.java
public class AppActivity extends Cocos2dxActivity
{
private Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.activity = this;
showToast();
}
public void showToast()
{
activity.runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
Toast.makeText(activity, "Hello :D", 10).show();
}
});
}
}
This works very nice in cocos2d-x version 3.x
I test it. Of course JNI just will call the method and this must work.
Related
I am playing with JobIntentService, and the docs have this example:
#Override
protected void onHandleWork(Intent intent) {
...
toast("Executing");
...
}
#Override
public void onDestroy() {
super.onDestroy();
toast("All work complete");
}
final Handler mHandler = new Handler();
// Helper for showing tests
void toast(final CharSequence text) {
mHandler.post(new Runnable() {
#Override public void run() {
Toast.makeText(JsInvokerJobService.this, text, Toast.LENGTH_SHORT).show();
}
});
}
I am new to Android, and I don't understand why they wrap Toast.makeText in a Runnable and don't use it directly in the onHandleWork and onDestroy methods. The docs for Runnable don't really help. Is this specific to JobIntentService or not? What stuff should go into the onHandleWork method and what should be offloaded to a Runnable ?
I am new to Android, and I don't understand why they wrap
Toast.makeText in a Runnable
It is because JobIntentService runs on Background thread and the Toast can't be shown from it. The handler will post in the runloop queue of the ui thread your runnable and it will get executed on it
Right now I have one thread which populates the view of my activity. But I want another thread to add some textviews and imageviews in the same activity. I am using SurfaceView inside which I created this thread and I don't know how to add another thread so that it can contribute to the view of the current activity.
Help me out..
MyView view;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
view = new MyView(this);
setContentView(view);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
view.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
view.resume();
}
public class MyView extends SurfaceView implements Runnable {
Thread threadstill = null;
boolean isitok = false;
SurfaceHolder holder;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
#Override
public void run() {
// TODO Auto-generated method stub
while (isitok == true) {
if (!holder.getSurface().isValid()) {
continue;
}
canvas = holder.lockCanvas();
canvas.drawARGB(255, 255, 255, 255);
canvas.drawBitmap(<bitmapimage>, x, y, null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
isitok = false;
while (true) {
try {
threadstill.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
threadstill = null;
}
public void resume() {
isitok = true;
threadstill = new Thread(this);
threadstill.start();
}
}
You cannot directly manipulate the user interface from another thread.
The main thread is responsible for all UI changes.
However, if you want to perform some expensive work in the background (e.g. loading pictures) you can send the results to the UI thread.
Hava a look at the official documentation: https://developer.android.com/training/multiple-threads/communicate-ui.html
Or at a similiar question: How can I manipulate main thread UI elements from another thread in Android?
I don't exactly know what is your issue but regarding to I don't know how to add another thread so that it can contribute to the view of the current activity. you can create a new thread easily with a nested class...simply call:
Thread myNewThread = new Thread(new Runnable() {
public void run() {
//do code here
}
}).start();
But be Aware you can only change views from the UIThread so i would recommend you the AsyncTask:
public void myAsyncTask exstends Asynctask<Void,Void,Void> {
....
}
AsyncTask Comes with several methods the most important is the doInBackground where you can do the heavy things like Network Connections or other stuff which would freeze the UI or is simply not allowed on the UIThread(Network stuff).
After doInBackground is finished onPostExecute is called which runs on the UiThread and where you can process changes on your views.
To get more Information look at this link:
http://developer.android.com/reference/android/os/AsyncTask.html
Hope it helps and it is what you asked for. ;)
Do it with AsyncTask class. In doInBackground method download image, and in onPostExecute method apply image to ImageView.
I did it here already https://github.com/bajicdusko/AndroidJsonProvider/tree/master/app/src/main/java/com/bajicdusko/ajp/tools.
You can use my class or make your own .
I'm fairly new to Android programming.
Simple Explanation for my problem:
I have an async task to collect JSON based data after every 20 seconds based on this runnable:
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
mTask = new JSONParse();
mTask.execute();
handler.postDelayed(this, 20000);
}
};
How do I stop it when I want to?
Detailed Explanation for my Problem:
Within this Async Task, I check if the data is available, and if not available, I go back to the mainscreen by first invoking
mTask.cancel(true);
and then in the onCancelled() method as follows:
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
mTask.cancel(false);
pDialog.dismiss();
displayWrongPhoneToast();
}
where displayWrongPhoneToast() is a simple function as follows:
public void displayWrongPhoneToast() {
Toast.makeText(getApplicationContext(),
"Sorry! Enter at least one field to continue.",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(TabActivity.this, MainActivity.class);
startActivity(intent);
}
The problem I have is, the handler is causing the runnable to execute in the background, which is making the application request data over and over again and causing the displayWrongPhoneToast() to execute over and over again.
I tried some methods I found online to stop the runnable, but it refuses to. Any help is appreciated. Thanks :)
You have to call
handler.removeCallbacks(r).
How can I write command in onclicklistener() so that I can move to next activity as well as my post status dialog will appear on that new activity. I am using intent for switching to next activity and also using postTowall() method. But these two doesn't perform simultaneously. I am using this method:
public void onClick(View v) {
// TODO Auto-generated method stub
postTowall();
Intent intent= new Intent(Frnd.this,Logout.class);
startActivity(intent);
}
private void postTowall() {
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
public void onComplete(Bundle values) {
String sh = null;
Bundle params = new Bundle();
params.putString("caption", sh);
}
public void onCancel() {
// TODO Auto-generated method stub
}
You can use thread for posting. Use asynctask and inside that post the message to face book. Or you may just write a simple thread and start it.
This asynctask link may help you. it has usage example also:
http://developer.android.com/reference/android/os/AsyncTask.html
You should set other activity to open post dialog. Send via intent a signal if it should or not...
I'm trying to receive message from my php server by creating a thread in a service but it doesnt work. can't go in the while loop and the error message as title shows. Please Help.
//Set the schedule function and rate
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
private void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
String flag = receivermessage();
while (flag.equals("N")){
notifyUser();
}
Log.d(TAG, "Download Successful");
}
}, 0, 10000);
better to use asynctask and receive msg inside asynctask doinbackground() mtd.As webservice call may take more time that u can't block main thread for more than 5sec in android.