android app not responding with using thread - android

I implemented a program that have a UI. In UI I have 2 button (start and finish). When I clicked start button my service in my app run, and with finish button my service finished.
In my service I connected to xmpp server, when speed of internet is high I don't have any problem, but when speed of internet is low, it takes a long time to connect xmpp server and my UI don't do any thing and crashed. I put connecting to xmpp server in a thread.
my code is:
public class FirstAct extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
btnStart.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(act, MainActivity.class));
}});
btnEnd.setOnClickListener( new OnClickListener() {
#Override
public void onClick( View v ) {
stopService(new Intent(act, MainActivity.class));
}});
}
}
//------------------------
public class MainService extends Service {
#Override
public void onStart(Intent intent, int startId) {
....
toastHandler2.sendEmptyMessage(0);
....
}
private final Handler toastHandler = new Handler() {
#SuppressWarnings({ "null","unused" })
#Override
public void handleMessage(android.os.Message msg){
try{
connectToXmppServer();
}catch(Exception e){
}
}
};
what should I do that, when ConnectToXMPP takes a long time, all of program not crashed???
please help me

I solved my problem with this thread instead of Handler:
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
connectToXmppServer();
}
}).start();
}

Related

Implementing Timer Task makes the application to crash

I am developing an application in which I want to implement timer task to print a toast message every 5 seconds. The problem is my application crashes after 5 seconds when i run it.Below is part of my code please tell me where I am making mistakes and how can I overcome it.
public class main_activity extends Activity implements BluetoothLeUart.Callback{
public ImageButton fabbutton;
Activity activity;
Timer time;
TimerTask timetask;
Handler handle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
fabbutton = (ImageButton) findViewById(R.id.fabbutton);
startTimer(); //this is where I start my timer task
fabbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanLeDevice(false);
Intent intent = new Intent(getApplicationContext(), ScanList.class);
startActivity(intent);
}
});
}
public void startTimer(){
time = new Timer();
initializeTimerTask();
time.schedule(timetask, 5000, 10000);
}
public void initializeTimerTask(){
timetask = new TimerTask() {
#Override
public void run() {
handle.post(new Runnable() {
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (time != null) {
time.cancel();
time = null;
}
}
}
you forgot to initialize handler,
Just add below line in oncreate or startTimer();
handle = new Handler();
Or even in your case you can use,
runOnUiThread(new Runnable(){
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});

how to stop the toast message after stop executing the program

public class Home extends ActionBarActivity {
public static final String PREFS_NAME="LoginPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("hello", "world");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please Enter the Details", Toast.LENGTH_SHORT).show();
}
});
}
}, 10, 10, TimeUnit.SECONDS);
}
Create a custom global object
private Toast toast;
Initialize it in onCreate
toast = Toast.makeText(YOUR_CLASS_NAME.this, "", Toast.LENGTH_SHORT);
Whenever you need to show a Toast
toast.setText("Text...");
toast.show();
To kill all the message based on requirement onPause or onDestroy
toast.cancel();
The problem with your code is that you don't stop the scheduler.
When you close the Activity the Application doesn't stop so the scheduler keeps running.
You can rewrite the code to stop the scheduler when activity stops and to start the scheduler when activity starts (instead of creation).
public class MainActivity extends ActionBarActivity {
private ScheduledExecutorService mScheduler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
mScheduler = Executors.newSingleThreadScheduledExecutor();
mScheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i("hello", "world");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please Enter the Details", Toast.LENGTH_SHORT).show();
}
});
}
}, 5, 5, TimeUnit.SECONDS);
}
#Override
protected void onStop() {
mScheduler.shutdown();
super.onStop();
}
}
Override onBackPressed() method in your activity, place this:
System.exit(0);
this is basically used to exit but this also stop the toast. try this.

Show Toast in a Thread of a Service

Hi i know there are lot of answers to this topic. But I tried a lot and it doesn't work. I want to show a toast inside a thread of a service. How can i solve this problem. Using getApplicationContext() etc. doesn't work.
I start the Service from an Activity (no bounding).
public class CarDataService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
startThreadUpdatingDatabase();
Toast.makeText(this, message, Toast.LENGTH_LONG).show(); //it works
}
private void startThreadUpdatingDatabase(){
Log.d("Database", "startThreadUpdatingDatabase(was called)");
new Thread(new Runnable() {
public void run(){
..
// here i want to use a toast!!!
}
}).start();
}
}
Thank you!
You have to start the thread:
new Thread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Your message",Toast.LENGTH_LONG).show();
}
}).start();
public Contect context;
member variable
onStartCommand(){
context = getApplicationContext)
}
acquivre reference to the context before you start the thread
new Thread(new Runnable() {
#Override
public void run() {
Toast.makeText(context,"Your message",Toast.LENGTH_LONG).show();
}
}).start();
and there you go
use AsyncTask instead that helps in context management
http://www.androidsnippets.com/use-toast-wherever-you-want
Handler h = new Handler(context.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
});
see if this works out
Show your Toast using UI-Thread
new Thread(new Runnable() {
#Override
public void run() {
// SHOW TOAST
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(yourContext, "Hello from UI-thread", Toast.LENGTH_SHORT).show();
}
});
//... start DB work
}
}).start();
If you have no access to an activity, so do it this way:
new Thread(new Runnable() {
#Override
public void run() {
// no activity, so use Handler & mainlooper
new Handler(Looper.getMainLooper()).post(
new Runnable() {
public void run() {
// yourContext is Activity or Application context
Toast.makeText(yourContext, "Hello from UI-thread", Toast.LENGTH_SHORT).show();
}
}
);
//... start DB work
}
}).start();
Look at this: Static Way to get Context on android?

How to navigate to another layout if the android app is inactive for 5 minutes

I am working on an android application. If the application is inactive or not using for 5 minutes, it should navigate to another activity. I have no idea about this. Please help. Thanks in advance.
Try adding the following code in your activity..
CODE
public static final long DISCONNECT_TIMEOUT = 300000;
// 5 min = 5 * 60 * 1000 ms=300000
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
Intent i=new Intent(this,newActivity.class);
startActivity(i);
}
};
public void resetDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
super.onStop();
stopDisconnectTimer();
}

Reload Activity after every 2 minutes

I want to reload my activity after every 1 minute. I tried using handler for this... but problem is that when i press back key of device, it doesn't stop and goes into an infinite loop..
here is my code what i have done--
public class Chat extends Activity {
Handler handler;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.chat);
handler = new Handler();
Toast.makeText(getApplicationContext(), "again", 400).show();
doTheAutoRefresh();
}
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
public void run() {
Intent intent = getIntent();
startActivity(intent);
finish();
//doTheAutoRefresh();
}
}, 10000);
}
public void onPause() {
super.onPause();
}
}
You should do this to remove all handler's messages and callbacks:
public void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null);
}

Categories

Resources