I'm not good at English, so I'm asking through translation.
Please understand even if the grammar is weird.
Developed USB communication App.
But often shutdowns are occurring.
We cannot find the cause because it is not a termination phenomenon due to a specific action.
Debugging is not possible because a USB communication device is connected.
Even if it is applied to most actions to create a log.txt file with a try-catch statement, it is not recorded in the log.
I also wrote a code for when the app is forcibly closed.
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
class ExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread t, Throwable e) {
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(filePath+"/Log.txt", true));
buf.append("Error!! : "+e.getMessage());
buf.close();
} catch (FileNotFoundException ee) {
ee.printStackTrace();
} catch (IOException ee) {
ee.printStackTrace();
}
e.printStackTrace();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
Even if I do this, it is not recorded in the log. Please advise on other methods.
Related
I newbie to Android development and I have a question.
I already look for this question in forum but no luck.
My MainActivity onCreate tries to connect to a sever.
In some cases the server can be down, and in this case, my app throw exception.
What should I do to finish the Activity gracefully?
I have tried to Toast a message and to finish() the activity but no message appears and the activity still running.
Whats wrong with my code ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mSocket = new Socket("127.0.0.1", 6000);
try {
conn = new ClientConnection(mSocket.getInputStream(),mSocket.getOutputStream());
GameSurfaceView gameSurface = (GameSurfaceView)findViewById(R.id.Game);
conn.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e) {
Log.e(TAG, "Unknown Host Exception");
e.printStackTrace();
Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT);
finish();
} catch (IOException e) {
Log.e(TAG, "IO Exception");
Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
finish();
}
catch (Exception e) {
Log.e(TAG, "Exception");
Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
finish();
}
Log.v(TAG,"Activity created");
}
Don't ever run network code in the UI thread. onCreate is the UI thread - You should never do any IO, network or other long processing task there. Read http://developer.android.com/training/best-background.html for more details.
Your toast is in the catch clause of the out try block - however all IOExceptions (including the UnknownHostException) are already caught in the inner try block. In there you only print the stack trace. That's why no message is ever shown. I don't see a need for two nested try blocks, one is probably all you need.
Assuming your app cannot run without server connection, the right approach would be to let the user know somehow that that's the case (AlertDialog, Toast, whatever) and then call Finish() on the activity to close it.
Edit: As pointed out in a deleted answer, calling show() is of course also needed in top of what I already mentioned:
Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT).show();
guys what are the best alternatives for Error Handling in android.
All in all I dont want my application to shutdown in first attempt.
Say it started, made a http request, error and closed.
I am looking for a warning type error and let it continue further functionality.
Thanks in advance.
when trying to print a stack trace you should always use this:
try {
// DO STUFF
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e);
}
Try Log.e(String, String);
Should work for you
try {
//Code
} catch (Exception e) {
System.out.println(e);
}
i am trying to connect a bluetooth device with my android app. so far its working fine.
Now the issue is when my device gets out of range , i am showing one dialog box and asking user to reconnect or not.
sometimes i am able to re-connect with the device and sometimes i do get error i.e.
Service Discovery Failed
and i really don't know why its happening
private class ConnectThread extends Thread {
public ConnectThread() {
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID);
} catch (IOException e) {
System.out.println("IO EXCEPTION" + e.getMessage() +"");
}
}
public void run() {
bluetoothAdapter.cancelDiscovery();
try {
// I AM GETTING ERROR HERE
bluetoothSocket.connect();
} catch (IOException connectException) {
Log.d("Exception : ConnectThread -> Run" , connectException.getMessage()+"");
try {
bluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
}
}
From experience, and actually having the same issue today,
If I was to speculate, I would say your other device, upon disconnection(link loss) does not immediately detect it has disconnected (it can take up to 30 seconds if I remember), or it just behaves badly.
Thus, it does not readvertise the service on SDP (does not open the socket again), so when Android initiates the connection(as client) your server fails - has no open socket.
You should post the other device logs. And try with a different other device - but same Android phone and code!
Again, just a guess.
I had the same problem; my solution may be specific to the device I am using, but I found that by sleeping the thread for 1000ms between the last communication to the socket and the socket.close(), it would restart successfully.
I have some piece of code. In that there are chances to get many number of exceptions. My doubt is, to handle all those exceptions do i have to write catch blocks for each type of exception. Is it an efficient way or not. Except using throws keyword, If any other solutions are there please suggest me to do that. Any response will be appreciated.
Thanks in advance
It depends on what kind of exceptions you're trying to catch. Everything that can be thrown implements Throwable, so you can catch everything with
} catch (Throwable t) {
including run time errors and all. As Amjad mentions, you can narrow that a little with
} catch (Exception e) {
which just catches Exception and its subtypes.
The problem with both of these is that they catch too much; you can work around that but you risk catching an important problem and then not handling it.
If you have just a few different exceptions, you're probably best off with an exception comb
} catch (Exception1 e) { // do something
} catch (Exception2 e) { // do something else
You have one other option if these are your own exceptions: make a class hierarchy of your own exceptions
class MyExceptions extends Exception { /* ... */ }
class MyExceptionSubtypeA extends MyException { /* ... */ }
class MyExceptionSubtypeASubsub1 extends MyExceptionSubtypeA { /* ... */ }
Now you can pick any subtree of classes, as with
} catch (MyExceptionSubtypeA sa) {
which will catch both MyExceptionSubtypeA and MyExceptionSubtypeASubsub1.
Use the general kind of exception Exception
try{
//your code here
}
catch(Exception e){
//handle exception
}
However this is unrecommended http://source.android.com/source/code-style.html#exceptionsAll
I was reading the the Android Publishing docs and they said to remove all Log calls from my code. I have some calls to e.printStackTrace() in my code that can be printed as part of the normal running of my program (ie. if a file does not exist yet).
Should I also remove these calls?
You shouldn't be using e.printStackTrace() directly anyway — doing so will send the info to the Android log without displaying which application (log tag) it came from.
As others have mentioned, continue to catch the Exception in question, but use one of the android.util.Log methods to do the logging. You could log only the message, but not the stack trace, or use verbose logging for the stack trace:
try {
Object foo = null;
foo.toString();
} catch (NullPointerException ex) {
Log.w(LOG_TAG, "Foo didn't work: "+ ex.getMessage());
Log.d(LOG_TAG, Util.stackTraceWriter(ex));
}
You should strip DEBUG or VERBOSE log messages from your production builds. The easiest way is to use ProGuard to remove Log.[dv] calls from your code.
If you allow an Exception to propagate up to the OS then the OS will log it and also pop up a Force Close window, killing your application. If you catch it, then you can prevent your application from being force closed.
If you want your users to have the ability to send you errors that they are getting, then I would log the stack trace. They can then send you the log via an app like Log Collector.
If you want to avoid the possibility of exposing your stack trace information to your users, then catch the exception and don't log it.
I would use Log class for message out put. For logs that you think are important to stay in the app - use Log.i
for errors warning - Log.e Log.w
For you debug Log.d - and that you can turnoff on base on if your application is in debug mode.
http://developer.android.com/reference/android/util/DebugUtils.html
Well printStackTrace() will log it into the OS, causing your andorid (or computer) app to terminate (force close), instead, do something like this:
public void nullPointerExceptionCauser()
{
try
{
Object example = null;
example.toString();
}
catch (Exception e)
{
Logger.log(Level.SEVERE, "Caught Exception: {0}", e.getStackTrace());
}
}
in my modest opinion (I'm not an Android developer)
It should be nice. I don't know the logging options for Android but I'm sure you have some configurable thing to output (or not) your traces.
And if you don't do printStackTrace() Android will not be doing the dirty work of ignoring it.
:)
It's only a good-feeling (style) thing.
If you want to be secure i.e. not allow anyone snooping to read exception logs you can do something like
private void hideExceptionsInReleaseMode()
{
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
if(!BuildConfig.DEBUG)
{
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException(Thread thread, Throwable ex)
{
defaultHandler.uncaughtException(thread, new RuntimeException("Something went wrong :p"));
}
});
}
}
In order to use printStackTrace in a safer way I would use StringWrite and PrintWriter:
...
catch (final Exception e)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Log.e("TAG", sw.toString());
}
Or alternatively:
catch (final Exception e)
{
Log.e(TAG, Log.getStackTraceString(e));
}
Use this to remove the logs from release apk
if (BuildConfig.DEBUG) Log.d(TAG, "your meseage");