I am trying to upload via FTP a file in a set directory. The file is called "advancedsettings.xml".
The code works fine when used in the Async Task of an Activity, but when attempting to use a Service to carry out the exact same operations within an Async Task, the application crashes with the following error(s):
01-13 16:21:08.403 21134-21151/com.name.example.xx E/AndroidRuntime﹕
FATAL EXCEPTION: AsyncTask #1 Process: com.name.example.xx, PID: 21134
java.lang.RuntimeException: An error occured while executing
doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at
java.util.concurrent.FutureTask.finishCompletion(F utureTask.java:355)
at java.util.concurrent.FutureTask.setException(Futur eTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.jav a:242) at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTas k.java:231) at
java.util.concurrent.ThreadPoolExecutor.runWorker(
ThreadPoolExecutor.java:1112) at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare() at
android.os.Handler.(Handler.java:200) at
android.os.Handler.(Handler.java:114) at
android.widget.Toast$TN.(Toast.java:388) at
android.widget.Toast.(Toast.java:114) at
android.widget.Toast.makeText(Toast.java:273) at
com.name.example.xx.MyService$FTPUpload.doInBackgr
ound(MyService.java:58) at
com.name.example.xx.MyService$FTPUpload.doInBackgr
ound(MyService.java:55) at
android.os.AsyncTask$2.call(AsyncTask.java:288) at
java.util.concurrent.FutureTask.run(FutureTask.jav a:237)
************at android.os.AsyncTask$SerialExecutor$1.run(AsyncTas k.java:231)
************at java.util.concurrent.ThreadPoolExecutor.runWorker( ThreadPoolExecutor.java:1112)
************at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587)
************at java.lang.Thread.run(Thread.java:841) 01-13 16:21:08.473 862-862/? W/ContextImpl﹕ Calling a method in the system
process without a qualified user:
android.app.ContextImpl.sendBroadcast:1505
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.broadcastEvent:296
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.processDropBoxEntry:254
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.access$100:60
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector$1.onReceive:102 01-13 16:21:08.713 862-21154/?
E/android.os.Debug﹕ !#Dumpstate > sdumpstate -k -t -z -d -o
/data/log/dumpstate_app_error
Here is how I call the service from within my main activity (on button click):
Intent inetnt=new Intent(FileChooser.this, MyService.class);
startService(inetnt);
And here is the Service code:
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(MyService.this, "service start", Toast.LENGTH_LONG).show();
new FTPUpload().execute();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public class FTPUpload extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void...params) {
Toast.makeText(MyService.this, "Service FTP Upload Start", Toast.LENGTH_LONG).show();
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("host");
// Check your USERNAME e.g myuser#mywebspace.com and check your PASSWORD to ensure they are OK.
if (con.login("username", "password")) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
Random rand = new Random();
String randomIntString = String.valueOf(rand.nextInt()).replaceAll("-", "");
FileInputStream in = new FileInputStream("/storage/emulated/0/");
//con.makeDirectory("/" + randomIntString + "/");
con.storeFile("advancedsettings.xml", in);
in.close();
//PASS URL TO NEXT ACTIVITY AND LAUNCH NEXT ACTIVITY ON NOTIFICATION CLICK
} else {
}
} catch (
Exception e
)
{ //if file does not upload successfully, write an error log.
Toast.makeText(MyService.this, "An error occured, please report: " + e, Toast.LENGTH_LONG).show();
}
Toast.makeText(MyService.this, "Service FTP Upload Complete", Toast.LENGTH_LONG).show();
return null;
}
}
}
I can confirm I have declared the service in my Android Manifest file within the application tag, as follows:
<service android:name=".MyService"/>
Any ideas guys? Thank you so much in advance for your help! I'm so keen to get to the bottom of this.
K
Please do not access the main thread from doInBackground, like running a Toast. Use onPreExecute for this kind of opperation instead.
Toast.makeText(MyService.this,
"Service FTP Upload Start",
Toast.LENGTH_LONG).show();
doInBackground should/can not access the UI Thread. For your complete task Toasts try to return a value from doInBackground, you will get the returned value in onPostExecute where you can show your toasts
For further Information have a look at the Documentation:
Documentation
Here
Toast.makeText(MyService.this, "Service FTP Upload Start", Toast.LENGTH_LONG).show();
You are trying to so Toast from doInBackground (from other Thread). use onPreExecute to show Toast before starting doInBackground execution
Related
I'm trying to run a function that requires passing it a screen capture. When I run this from the main activity, I can run the code like this:
SendScreenFunction(getWindow().getDecorView().getRootView(), getApplicationContext());
I'm not trying to call this function from a service and I can't access the getWindow() function because it requires an activity (which isn't available in the service). I was looking around online and someone suggested a function to get the activity so I can use the function. My current code looks like this:
public class ASTasks extends Service {
// This method run only one time. At the first time of service created and running
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
Log.d("onCreate()", "After service created");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Entered Timer!", Toast.LENGTH_SHORT).show();
Activity main_activity = getActivity(getApplicationContext());
try {
Log.i("Services", "Before crash");
SendScreenFunction(main_activity.getWindow().getDecorView().getRootView(), getApplicationContext());
Log.i("Services", "After crash");
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// We don't provide binding
return null;
}
public void SendScreenFunction(View view, Context context){
// Function goes here
}
public static Activity getActivity(Context context) {
if (context == null) return null;
if (context instanceof Activity) return (Activity) context;
if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
return null;
}
}
Unfortunately, that solution doesn't seem to work and it's crashing. The Logcat error is shown below:
Process: com.example.ASservice:remote, PID: 15966
java.lang.RuntimeException: Unable to start service com.example.ASservice.ASTasks#6e7fed5 with Intent { cmp=com.example.ASservice/.ASTasks }: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Activity.getWindow()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5110)
at android.app.ActivityThread.access$2100(ActivityThread.java:310)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window android.app.Activity.getWindow()' on a null object reference
at com.example.ASservice.ASTasks.onStartCommand(ASTasks.java:41)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:5092)
at android.app.ActivityThread.access$2100(ActivityThread.java:310)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Any ideas on the best way to take the screen capture from within the service (or even a way to pass a flag back to main to process it there)?
Any suggestions would be greatly appreciated. Thanks!
I've met with problems while testing a recording app on the emulator(Pixel 3a API 30)
Below is the Java code that I searched for in the tutorial on Youtube.
In the video it can be tested normally.
When it comes to me, it kept crashing when I hit on the stop recording button.
//Request Runtime Permission
if (!checkPermissionFromDevice())
requestPermission();
//Init view
pl_btn = (Button)findViewById(R.id.play_btn);
rcrd_btn = (Button)findViewById(R.id.record_button);
stp_rcrd_btn = (Button)findViewById(R.id.stop_record_btn);
ps_btn = (Button)findViewById(R.id.pause_btn);
//From Android M, need request Run-time permission
rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermissionFromDevice()) {
pathSave = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/"
+ UUID.randomUUID().toString() + "audio_record.3gp";
setupMediaRecorder();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
pl_btn.setEnabled(false);
ps_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
stp_rcrd_btn.setEnabled(true);
Toast.makeText(recording_and_play_test.this, "Recording...", Toast.LENGTH_SHORT).show();
} else {
requestPermission();
}
}
});
stp_rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaRecorder.stop();
stp_rcrd_btn.setEnabled(false);
pl_btn.setEnabled(true);
rcrd_btn.setEnabled(true);
ps_btn.setEnabled(false);
}
});
pl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ps_btn.setEnabled(true);
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(pathSave);
mediaPlayer.prepare();
}catch (IOException e){
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(recording_and_play_test.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
ps_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(true);
pl_btn.setEnabled(true);
ps_btn.setEnabled(false);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathSave);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
},REQUEST_PERMISSION_CODE);
}
And here's what the activity looks like
While I hit the stop recording button while executing the recording function, the app then just crashed and restarts again.
Here's what the build log says
E/MediaRecorder: stop called in an invalid state: 4
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.adrsingingscope, PID: 7309
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.adrsingingscope.recording_and_play_test$2.onClick(recording_and_play_test.java:88)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
This could be a problem with the path you created to save a file. These things can be easy to mess up. The media recorder has its own state and STATE 4 in which your app crashed in the state of recording. So it didn't stop and something happened in between that process so I assume it is related to saving your file to external storage.
You can find MEDIA_RECORDER_STATES here: https://android.googlesource.com/platform/frameworks/av/+/android-4.2.2_r1.2/include/media/mediarecorder.h#96
There are three things you can try.
Change your save file path
Try changing your path to a different directory. Sometimes you are trying to reach the directory you are not allowed to or it doesn't exist. More you can read in this answer: https://stackoverflow.com/a/33107120/14759470
Check your AndroidManifest.xml for permissions
Check if you wrote your permissions in AndroidManifest.xml as you should. You need WRITE_EXTERNAL_STORAGE and RECORD_AUDIO for this. In your code, it even says that from Android M (6.0) you need RUN_TIME permission. So just add them on top of your manifest file if you didn't.
Make your code better
Don't stop the recorder if it's already stopped. This will throw an exception. Don't release if already released, also an exception, and so on. So test your code for bugs, make breakpoints, and find your weak spots. It will be easier for you to find your errors. Also, check the log for more error messages since this one doesn't give us much.
I went to sleep yesterday with my app working and today when I tried to run it won't start at all. As soon as I try to open it crashes with a java.lang.IllegalStateException. I've gone several commits back in my code just to rule out it was something I did recently and still. This makes no sense, how can an app just stop working over night? I've looked for the error in the internet and there is not a lot of useful information about it. Is this really an odd error?
Here's the complete stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: AssetManager has been finalized!
at android.os.Parcel.readException(Parcel.java:1439)
at android.os.Parcel.readException(Parcel.java:1385)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1947)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.app.Activity.startActivity(Activity.java:3583)
at com.android.launcher2.Launcher.startActivity(Launcher.java:2442)
at com.android.launcher2.Launcher.startActivitySafely(Launcher.java:2469)
at com.android.launcher2.AppsCustomizePagedView.onClick(AppsCustomizePagedView.java:584)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Since like I said it doesn't seem to be anything that I did I'm not sure what code to post. But given that the app crashes on start here's the code for the two main classes that are supposed to start first:
App
public class App extends Application {
private static App instance;
private static final String TAG = "Starter";
#Override
public void onCreate() {
super.onCreate();
instance = this;
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
//TODO: Register subclasses
// ParseObject.registerSubclass(Challenge.class);
//Parse server
Log.d(TAG, "Initializing Parse");
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(getString(R.string.parse_app_id))
.clientKey(getString(R.string.parse_client_key))
.server(getString(R.string.server_address)).build()
);
//Facebook
if (AccessToken.getCurrentAccessToken() == null)
ParseFacebookUtils.initialize(this);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Log.d(TAG, "Parse ready");
}
public static App getInstance(){
return instance;
}
}
SplashActivity
public class SplashActivity extends AppCompatActivity {
private static final String TAG = "Splash";
private boolean firstTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
firstTime = getSharedPreferences(Constants.GENERAL_SHARED_PREFS, MODE_PRIVATE)
.getBoolean(Constants.FIRSTTIME, true);
if (isLoggedIn())
if (firstTime)
startActivity(new Intent(SplashActivity.this, FirstTimeActivity.class));
else
startActivity(new Intent(SplashActivity.this, MenuActivity.class));
else {
Log.d(TAG, "Calling Home");
startActivity(new Intent(SplashActivity.this, WelcomeActivity.class));
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
String parseSession = ParseUser.getCurrentUser().getSessionToken();
return parseSession != null;
}
}
Your stacktrace links to this class in the AOSP.
I think this crash has nothing to do with your app, but as an error in the Launcher class. Try installing from USB debugging and see if that works.
But there are still some details that are blurry. These lines are (from bottom of the stacktrace to the top) the lines that cause problems in com.android.launcher2 package:
https://android.googlesource.com/platform/packages/apps/Launcher2/+/android-4.2.2_r1/src/com/android/launcher2/AppsCustomizePagedView.java#584
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2469
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2442
From this error, I assume you are using a Nexus or Pixel (or any device with the unaltered source code, meaning stock android.).
From what I can tell from this error, this is not an error related to your app. It appears to be an issue with the launcher you are using. Try installing from USB debugging, or change launcher, and see if that works. Try rebooting your device as well.
Further, from what I see of your code, there are no parcelable classes in use
This error can also be caused when Instant Run loses connection with the Android Emulator as a result of which new app changes are not persisted in the emulator.
Running the app again will solve the issue.
I'm getting a FATAL EXCEPTION: main when I run the app. It run first but for a few seconds it crash.
Here is my Logcat :
java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
at android.view.InputChannel.nativeReadFromParcel(Native Method)
at android.view.InputChannel.readFromParcel(InputChannel.java:148)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:752)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:527)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.AlertDialog$Builder.show(AlertDialog.java:993)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:545)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:212)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Inside my ActivityMain.java:542 in alrt.show() this is where the logcat point it:
#Override
protected void onPostExecute(Boolean result) {
Log.i(TAG, "onPostExecute");
super.onPostExecute(result);
if(result){
Log.i(TAG, "TASK IS DONE");
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
app.saveToLastPref(ActivityMain.this, app.PREFS_PREV_VERSION, pInfo.versionName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), ActivityMenuPage.class);
startActivity(intent);
finish();
}else{
ActivityMain.this.deleteDatabase("DBSHAKEYS");
Builder alrt = new AlertDialog.Builder(mcontext);
alrt.setMessage("Update failed. Please check your internet connection and try again.");
alrt.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alrt.show();
}
}
}
And in ActivityMain.java:212 :
public class ProcessData extends AsyncTask<Void, Void, Boolean>
I think Builder is your custom class that you are using now to show the AlertDialog.
Here is what may happened
The onPostExecute() method was called automatically after your some background process was finished executing. And then It tried to use the Builder class which may be currently being used by another process and still running in the memory.
How can it be solved then ?
Review your code and see if the dialog is already being shown using
Builder class.
Simply change this line
Builder alrt = new AlertDialog.Builder(mcontext); to normally AlertDialog.Builder alrt = new AlertDialog.Builder(mcontext);
and see if this works.
I am starting two asynchronous task in two diffrent services first one works correctly and opens a socket but second one is not starting here is the code my application is based on client socket programing in wifip2p.
public class RecieveAudioService extends Service {
String tag = "Recieve Audio Service";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Recieve audio :requesting to client", Toast.LENGTH_LONG).show();
String[] param = {"h", "j", "k"};
new request().execute();
Log.v("Recieve Audio", "Inside Recieve audio service");
return super.onStartCommand(intent, flags, startId);
}
//===================== This class is sending request to server for connection when invocked
public class request extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
Log.v("second asyn", "this is second asynchronous task");
try {
Toast.makeText(getApplicationContext(), "Request to connect sent to server",
Toast.LENGTH_LONG).show();
String toConnectDeviceIP = "192.168.49.1";
Integer toConnectDevicePort = 8988;
Socket connect = new Socket();
connect.bind(null);
connect.connect((new InetSocketAddress(toConnectDeviceIP, toConnectDevicePort)),
5000);
Log.v(tag, "sent the connection request to clint");
connect.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v(tag, "" + e.toString());
Toast.makeText(getApplicationContext(), "i found exception in connection"
+e.toString(), Toast.LENGTH_LONG).show();
}
return "success";
}
}
//====================================================================
}
It seems that you launch your app on Android 4.x/3.x. Before Android 3.0 AsyncTasks ran concurrently but later versions(>3.x) of system executes tasks one after another. So you have two choices:
a) Use Threads instead of AsyncTasks
b) Use executeOnExecutor of AsyncTask to execute tasks concurrently:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}