I searched many places but could not find a complete working example of implementation of "runOnUiThread". I tried a lot , but getting lots of errors .
I just want to display a toast from a thread.
So here is the final full code. Thanks to all who have replied.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}
});
}
}
And About the XML, its is the default XML file created. No change needed.
YourActivityName.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(YourActivityName.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}
});
To answer Nefariis question, I had the same problem, and needed to toast from a non-activity class, to solve it you can pass Context to the function your calling runOnUiThread from.
For example:
public class FlashCardsUtil
{
public static void fillTableFromFile(SQLiteDatabase pSqLiteDatabase, final Context pContext, String pFileName)
{
...
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(pContext, "Success filling database", Toast.LENGTH_SHORT).show();
}
});
}
}
Related
Is it possible to integrate video ads from Flurry in an android app? I tried some things, but it didn't work. The Flurry Android SDK has the onVideoCompleted function, and in the Android Flurry SDK Release Notes, the following can be found: verified support for clips in AdUnity (http://support.flurry.com/index.php?title=Analytics/Code/ReleaseNotes/Android).
I tried this code, but it didn't work for me:
package com.test.flurrytest;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import com.flurry.android.FlurryAdType;
import com.flurry.android.FlurryAds;
import com.flurry.android.FlurryAdSize;
import com.flurry.android.FlurryAgent;
import com.flurry.android.FlurryAdListener;
public class MainActivity extends Activity implements AdCallbackListener, FlurryAdListener {
FrameLayout mBanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBanner = new FrameLayout(this);
FlurryAds.setAdListener(this);
FlurryAds.enableTestAds(true);
Button watchvideo = (Button) findViewById(R.id.watchvideo);
watchvideo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FlurryAds.fetchAd(MainActivity.this, "TestAdspace", mBanner, FlurryAdSize.FULLSCREEN);
FlurryAds.displayAd(MainActivity.this, "TestAdspace", mBanner);
}
});
}
// Flurry
#Override
public void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "****");
}
public void spaceDidReceiveAd(String adSpace) {
FlurryAds.displayAd(this, adSpace, mBanner);
}
public void onVideoCompleted(String adSpace) {
// The user get some points now
}
public boolean shouldDisplayAd(String adSpaceName, FlurryAdType type) {
return true;
}
public void onAdClosed(String adSpaceName) {
}
public void onRenderFailed(String adSpaceName) {
Toast.makeText(getApplicationContext(), "The video has failed to render. Try again.", Toast.LENGTH_LONG).show();
}
public void onApplicationExit(String adSpaceName) {
}
public void spaceDidFailToReceiveAd(String adSpaceName) {
Toast.makeText(getApplicationContext(), "Failed to receive ad. Try again.", Toast.LENGTH_LONG).show();
}
public void onAdClicked(String adSpaceName) {
}
public void onAdOpened(String adSpaceName) {
}
#Override
public void onStop() {
super.onStop();
FlurryAds.removeAd(this, "TestAdspace", mBanner);
FlurryAgent.onEndSession(this);
}
}
Is it possible with Android, and if so, how to integrate it?
Thanks!
I am trying to implement a service in Android that displays a toast message every 1 minute in Android. I am new to Android development and learned about AlarmManager that will help me do this. I have implemented the code in the following way:
This is my IIManagerActivity class
package com.example.iimanager;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.widget.Toast;
public class IIManagerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_iimanager);
AlarmManager mgr=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(this, SampleService.class);
PendingIntent pi=PendingIntent.getService(this, 0, i, 0);
mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES/900, pi);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_iimanager, menu);
return true;
}
}
And this is my SampleService that is meant to display a toast message.
For some reason I cannot get to see a toast message no matter how long I wait.
package com.example.iimanager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class SampleService extends IntentService {
public SampleService() {
super("SimpleService");
//Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
#Override
protected void onHandleIntent(Intent intent) {
//do something
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
}
Can you please tell me what's wrong and what needs to be done to get it corrected?
Thank you very much in advance.
Copy the below 3 lines for toast call
Timer timer = new Timer();
TimerTask updateProfile = new SampleService(SampleService.this);
timer.scheduleAtFixedRate(updateProfile, 10,1000);
class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
// Write Custom Constructor to pass Context
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
});
}
}).start();
}
}
Try following code,
MainActivity.java
public class MyService extends Service {
public static final long INTERVAL=60000;//variable for execute services every 1 minute
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("unsupported Operation");
}
#Override
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
#Override
public void onDestroy() {
Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
mTimer.cancel();//cancel the timer
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast at every 1 minute
Toast.makeText(getApplicationContext(), "Notify", Toast.LENGTH_SHORT).show();
}
});
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
startService(new Intent(this,MyService.class));//use to start the services
}
}
Also add this code in your manifest file
AndroidManifest.xml
<service android:name=".MyService"
android:enabled="true"/>
Try to create a Timer object.Then use the scheduleAtFixedRate(TimerTask) to repeat the Toast message.
You can just make a looping thread which contains your code.
Like this:
public class Toaster extends Thread{
public void run(){
//Your code to loop
thread.sleep(60000)
}
}
Hope it helps!
Why Am I Getting This Error In Threads?
I have used the correct syntax, but it seems there is some error! :(
Here is the Screenshot ==> http://i.imgur.com/ccPOz.png?1
EDIT: Here's the code:
`
package com.pc.threads;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread music_2 = new Thread(){
try{
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent music_i = new Intent(MainActivity.this,NewActivity.class);
}
};
}
`
In Java, code goes inside methods. When you define (inline) your thread class, you forgot to define a method "run" that wraps your code.
Thread t= new Thread() {
public void run() {
///your code goes here
}
};
I have 3 button and 3 textview.When i press first button i want to see 10 sec later which is writing in the first textview.i press second button i want to see someting 5 sec later which is writing in the second textview .i press third button,i want to see textview which is writing immediately.
My question how can i work all multithread in the view without lock other view? I tried ASCYNTask but it doestn work.
Can anybody give me any suggestion?
My Activity:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity
{
Button a,b,c;
TextView ta,tb,tc;
Ascyn ascyn,ascyn2,ascyn3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a=(Button)findViewById(R.id.ba);
b=(Button)findViewById(R.id.bb);
c=(Button)findViewById(R.id.bc);
ta=(TextView)findViewById(R.id.ta);
tb=(TextView)findViewById(R.id.tb);
tc=(TextView)findViewById(R.id.tc);
ascyn=new Ascyn(this);
ascyn2=new Ascyn(this);
ascyn3=new Ascyn(this);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn.execute();
SystemClock.sleep(5000);
ta.setText("ok");
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn2.execute();
SystemClock.sleep(1000);
tb.setText("ozaman");
}
});
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn3.execute();
tc.setText("byby");}
});
}
}
Ascyn:
package com.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
/**
* Created by IntelliJ IDEA.
* User: duygukahraman
* Date: 20.02.2012
* Time: 15:44
* To change this template use File | Settings | File Templates.
*/
public class Ascyn extends AsyncTask<Void,String,Void> {
private Context ctx;
ProgressDialog dialog;
public Ascyn(Context context){
ctx=context;
dialog=new ProgressDialog(ctx);
}
#Override
protected void onPreExecute() {
// dialog.setTitle("Please wait");
// dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// SystemClock.sleep(20000);
return (null);
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
You have to create separate Async class for each thread like.
public class AscynThread1 extends AsyncTask<Void,String,Void> { // }
public class AscynThread2 extends AsyncTask<Void,String,Void> { // }
public class AscynThread3 extends AsyncTask<Void,String,Void> { // }
You don't need threads, if you simply want to write some text in a textview. Use a handler instead.
Handler handler = new Handler();
public void method() {
handler.postDelayed(new Runnable() {
public void run() {
textView.setText("Your text");
}
}, 5000);
}
I want to display toast message inside timer and I used the following code :
timer.scheduleAtFixedRate( new TimerTask()
{
public void run()
{
try {
fun1();
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);
public void fun1()
{
//want to display toast
}
And I am getting following error:
WARN/System.err(593): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
WARN/System.err(593): at android.os.Handler.(Handler.java:121)
WARN/System.err(593): at android.widget.Toast.(Toast.java:68)
WARN/System.err(593): at android.widget.Toast.makeText(Toast.java:231)
Thanks.
You can't make UI updates inside separate Thread, like Timer. You should use Handler object for UI update:
timer.scheduleAtFixedRate( new TimerTask() {
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
fun1();
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);
The easiest way (IMO) is:
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
final String message = "Hi";
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
});
The key being MyActivity.this.runOnUiThread(Runnable).
create a Handler and display toast in this
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Toast here
}
};
You need access to the Context of the application to be able to do this. Try creating your own class which takes the context as input parameter:
private class MyTimerTask extends TimerTask {
private Context context;
public MyTimerTask(Context context) {
this.context = context;
}
#Override
public void run() {
Toast.makeText(context, "Toast text", Toast.LENGTH_SHORT).show();
}
}
Then in your timer:
timer.scheduleAtFixedRate( new MyTimerTask(this), 0,60000);
I wanted to make a simple project that could display a Toast in a Timer.
The Timer would be started using a service. Then, the Timer starts when the service is started and stops when service is stopped.
Class 1
package com.example.connect;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Connect_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Connect_service.class));
}
}
Class 2
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Connect_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Connect_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 5000);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Class 3
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "In Timer", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
I'm trying to make my own toast with my own views.
I've successfully combined your approaches. The following code allows me to show toasts and change/remove views without crashing, just change the parameters of the MyTimerTask constructor to whatever you need to work on.
public void yourFunction(){
Timer timer = new Timer();
MyTimerTask mtc = new MyTimerTask(this.getContext(), tvNotice);
timer.schedule(mtc, 1000);
}
private class MyTimerTask extends TimerTask {
private TextView tv;
private Context context;
public MyTimerTask(Context pContext, TextView pTv) {
this.tv = pTv;
this.context = pContext;
}
#Override
public void run() {
updateUI.sendEmptyMessage(0);
}
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
tv.setText("TextView Message");
Toast.makeText(context, "Toast Message", 0).show();
}
};
}
You have to call UIThread for showing Toast, not from timer thread.
Else call UI thread from that timer thread.
This link will help you,
http://developer.android.com/resources/articles/timed-ui-updates.html
and this
http://developer.android.com/guide/appendix/faq/commontasks.html#threading