How to check in android how a program crashed? - android

Is there a tooling or maybe a log, where I can see what caused my application running on a android mobile phone, to hung or eventually crash?
I have programmed a signed application that is a runnable, it checks for messages on my server and send sms messages to a receiver, and after two or maybe 3 days, the application hungs or crashes.
How can I see what caused the crash?
Regards.
Shafqat
private void startservice() {
r = new Runnable()
{
public void run()
{
//execute the sms class and get the url
//build the url
SendSMS sms = null;
//TODO get the url from a database
Map<String, String> jsonitems = new JSONParser().parse(urlsmsservice+getDeviceId());
if(!jsonitems.isEmpty()){
sms = new SendSMS(context, jsonitems.get("PHONENUMBER").toString(), jsonitems.get("MESSAGE").toString());
sentReceiver.setCallbackUrl(jsonitems.get("CALLBACKURL").toString());
deliveredReceiver.setCallbackUrl(jsonitems.get("CALLBACKURL").toString());
sms.send();
}else{
Log.d(TAG, "No messages in Queue");
}
//handler.postDelayed(this, getInterval());
}
};
handler = new Handler();
thread = new Thread()
{
#Override
public void run() {
try {
while(thbool) {
sleep(getInterval());
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}

Make sure ADB tools are installed (they will be with the SDK). Then run adb logcat, which will show the system log output (useful is an exception is thrown). There are also free market applications which will show you the logcat buffer (aLogCat comes to mind).

Related

Linphone core listener not receiving incoming calls

I was trying to add sip incoming calls with linphone sdk, The registration is successful and I can make out going calls and the call status is logging as expected, but I am not able to receive incoming calls. I am using intent service to handle connection.
Here is my code:
protected void onHandleIntent(Intent intent) {
String sipAddress = intent.getStringExtra("address");
String password = intent.getStringExtra("password");
final LinphoneCoreFactory lcFactory = LinphoneCoreFactory.instance();
// First instantiate the core Linphone object given only a listener.
// The listener will react to events in Linphone core.
try {
lc = lcFactory.createLinphoneCore(new LinphoneCoreListenerBase() {
#Override
public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
super.callState(lc, call, state, message);
Log.i(TAG, "callState: ");
}
}, getApplication());
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
lc.setUserAgent("Test app", "1.0");
try {
LinphoneAddress address = lcFactory.createLinphoneAddress(sipAddress);
String username = address.getUserName();
String domain = address.getDomain();
if (password != null) {
lc.addAuthInfo(lcFactory.createAuthInfo(username, password, null, domain));
}
// create proxy config
LinphoneProxyConfig proxyCfg = lc.createProxyConfig(sipAddress, domain, null, true);
proxyCfg.setExpires(2000);
lc.addProxyConfig(proxyCfg); // add it to linphone
lc.setDefaultProxyConfig(proxyCfg);
running = true;
while (running) {
lc.iterate(); // first iterate initiates registration
sleep(20);
}
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
}
What is wrong with my code?
As the IntentService document (https://developer.android.com/reference/android/app/IntentService) stated:
the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
I think you should not put the listener in an IntentService. Instead, put it in a long running Service so that the listener can actually keep staying there to receive events.

SOCKS-5 proxy server on android device without root

Is there a way to create a SOCKS-5 proxy server on an unrooted android device? Why does it require root? Can I make my own android application that will create a server on my device and use this server as proxy on my compluter, all this without rooting the device?
UPDATE: I came to using this library to try to create a proxy server. I downloaded all files, but added only main .jar file to the project dependencies in AndroidStudio. There I am trying to start the server from a runnable in a service. Here is the service code:
public class ProxyService extends Service
{
private static boolean running = false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ServerAuthenticatorNone auth = new ServerAuthenticatorNone();
ProxyServer server = new ProxyServer(auth);
Run(server); //runnable is needed because if I start service from
//this thread it throws a network on main thread exception
return START_STICKY;
}
private void Run(ProxyServer server) {
if (running)
return;
final ProxyServer serverFinal = server;
running = true;
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Log.i("DEBUG", "tick " + running);
serverFinal.start(1080);
Log.i("DEBUG", "proxyServer started at port 1080");
running = true;
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
running = false;
}
}
}
}).start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
When I run this code on my Xiaomi Redmi Note 2 unrooted device, I get the following logs:
07-26 16:48:18.097: I/DEBUG(19766): tick true
07-26 16:48:18.099: I/XiaomiFirewall(1211): firewall pkgName:com.socks.server, result:0
And when I check proxy using this website I get nothing.
I think I should have configured the server somehow, but it is done using external .properties file that is outside of the .jar and I do not know how to link them in an AndroidStudio project.
I also suspect that even these actions require superuser(root) to prevent Xiaomi firewall from refusing me in starting the server.
Any advice?

Calling a "for" loop twice to print two receipts

I have a bluetooth printer integrated to my app and if I do some transactions, I can print the receipt to the customer. I have a method to handle the printing of receipts. Currently, I can print only one receipt but I would like to print the receipts twice.
Should I run the for loop twice so the method which prints my receipt is executed twice.
private void printReceipt(final Transaction transaction) {
showProgressPopup(getString(R.string.printing_dialog_message));
Runnable printThread = new Runnable() {
#Override
public void run() {
final BitSet resultBit = new BitSet(1);
try {
final ReceiptMetadata receiptMetadata =
AirFiUtils.getPaymentDeviceReceiptMetaData(getAirlineProfile(),
AirFiUtils.getMerchantAccount(getAirFiActivity()));
if (null != receiptMetadata) {
PrinterManager.printReceipt(PrinterType.valueOf(receiptMetadata.getPrinter().get(0)),
ReceiptType.CASH, receiptMetadata, transaction, getActivity().getApplicationContext(),
transaction.isSignatureCard());
resultBit.set(0, true);
}
} catch (Exception e) {
LOG.error("Error in printing ", e);
resultBit.set(0, false);
}
}
};
new Thread(printThread).start();
}
use for loop inside your if statement e.g
if(your_condition){
for(int i=0;i<2;i++){
//your desired code to print receipt
}}
or call your specific function two time which is need to be print receipt by applying for loop

Android to detect possibilities of no data connection

I have an application which needs to communicate with the server at some random interval through GPRS or EDGE.. But there are few possibilities at which internet cannot be accessed by the application when the user is in call or deactivated etc. At these time i have two scenario's recoverable and non recoverable.
Recoverable scenarios
On phone call ( User will hang up and data connection will be active
again)
No Signal (Sometimes signal may drop and the phone will get
signal again)
Non Recoverable Scenarios
Flight mode
Deactivating Data Connection
When its recoverable i can try again for the connection after some defined interval. And during non recoverable i have to alert user. For instance if the user deactivates data connection or enables flight mode i have to alert the user.
EDIT:I can able to detect flight mode through one of the intents. I couldn't able to find for others.
The below code return if valid connections are available
public boolean isConnectionsAvailable() {
boolean lRet = false;
try{
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info= conMgr.getActiveNetworkInfo();
if(info != null && info.isConnected()) {
lRet = true ;
}else{
lRet = false ;
}
}catch (Exception e) {
Log.d("Connection Error", e.toString());
lRet = false ;
}
return lRet;
}
After this, if you have low signal strength then you make a HTTP request by setting relevant time out to it. If timeout happened give relevant alert msg to user as below
public void serverCall(String pURL){
if (isConnectionsAvailable()){
// Call server by setting proper timeout
}
}
Edit:
To check the Airplane mode status:
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
You could try surrounding your method with try and catch. If the method fails because it cannot connect to your server for whatever reason you could call postDelayed from a Handler and re-run your method again in a pre-determined length of time.
Handler mHandler = new Handler();
Runnable yourMethodRunnable = new Runnable(){
#Override
public void run(){
yourMethod();
}
};
private void yourMethod(){
try{
// talk to server
} catch (InCallException e) {
mHandler.postDelayed(yourMethodRunnable, delay)
} catch (NoSignalException e) {
// etc...
} catch (OtherException e) {
// etc...
}
}
The exceptions are just examples, and likely don't exist, get the exceptions that you want to catch either from the Android Developer Docs, or by looking at the output from LogCat when you re-enact each time that the connection to the server would fail.

Thread loses Message after wait() and notify()

I have a problem handling messages in a Thread. My run-method looks like this
public void run() {
Looper.prepareLooper();
parserHandler = new Handler {
public void handleMessage(Message msg) {
Log.i("","id from message: "+msg.getData.getString("id"));
// handle message
this.wait();
}
}
}
I have several Activities sending messages to this thread, like this:
Message parserMessage = new Message();
Bundle data = new Bundle();
data.putString("id", realId);
data.putString("callingClass", "CategoryList");
parserMessage.setData(data);
parserMessage.what = PARSE_CATEGORIES_OR_PRODUCTS;
parserHandler = parser.getParserHandler();
synchronized (parserHandler) {
parserHandler.notify();
Log.i("","message ID: " + parserMessage.getData().getString("id"));
}
parserHandler.sendMessage(parserMessage);
The problem is that the run-method logs "id from message: null" though "message ID" has a value in the Log-statement. Why does the message "lose" it's data when being send to the thread? Has it something to do with the notify? Thanks for your help
So I think I figured out the problem. It was the MessageQueu in combination with an OnScrollListener I used in an other location of my code. The onScrollListener was called multiple times and so the MessageQueu was blocked with messages from this listener.

Categories

Resources