How to know the reachable of any url address? - android

I wrote the following method to know the reachable of url.
public boolean isMyURLReachable(String url){
boolean reachable = false;
try {
reachable = InetAddress.getByName(url).isReachable(2000);
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return reachable;
}
and I call it like that.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
boolean reachable = isMyURLReachable("www.google.com");
if(reachable)
Toast.makeText(getApplicationContext(), "Reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "Unreachable", 500).show();
}
});
But android.os.NetworkMainThreadException occur, do I need anything to put in my androidmanifest.xml file or my idea is being wrong?

NetworkMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.
Please try to perform that in an AysncTask or another thread.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

I wrote the following inner class.
class URLCheckTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... url) {
boolean reachable = false;
try {
reachable = InetAddress.getByName(url[0]).isReachable(7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(reachable)
return "1";
else
return "0";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("1"))
Toast.makeText(getApplicationContext(), "reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "unreachable", 500).show();
}
}
and call it from onClick() method.
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new URLCheckTask().execute("www.google.com");
}
});
No exception occur this time. But...., the result is not correct even though I can call it from emulator's browser, it always show me unreachable.

Related

Android file upload using ftp

Android file upload not working and not showing any error or any exception.
I want to add up some thing like check the internet connection when it is working only then it tries to upload the file and also want to add up one more thing that it makes a sync between server and application that this code will be called automatically after regular interval of time when the internet connection is working.
I have tried many jar files to upload the file and make an ftp connection but nothing works. jar file link http://www.jibble.org/files/simpleftp.jar
import org.jibble.simpleftp.SimpleFTP;
File file = new File("/sdcard/CreativeDroid/test.txt");
this way I am calling MyAsyncTask class to upload a txt file
new MyAsyncTask().execute(file.toString());
private class MyAsyncTask extends AsyncTask <String, Integer, Double> {
protected Double doInBackground(String... params) {
try {
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("www.creativetabs.co", 21, "username", "password");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
//ftp.cwd("web");
// Upload some files.
ftp.stor(new File(params[0]));
// Quit from the FTP server.
ftp.disconnect();
} catch (IOException e) {
Log.d("error", e.toString());
// TODO Auto-generated catch block
}
return null;
}
}
Try using ftp4j:
http://www.sauronsoftware.it/projects/ftp4j/
I have been using this since 3 years and it works flawless.
private int uploadFile() throws Exception {
long fileSize = 0;
boolean supported = ftp.isResumeSupported();
String fileName = getFileName(file_path);
String server_path = data.getServer_folder() + fileName;
try {
fileSize = ftp.fileSize(server_path);
} catch (Exception e) {
fileSize = 0;
}
if (fileSize == 0) {
ftp.upload(new java.io.File(file_path), new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
uploaded = uploaded + arg0;
Utilities.showDLog(Tag, "uploaded: " + uploaded);
}
#Override
public void started() {
Utilities.showDLog(Tag, "uplaod started");
}
#Override
public void failed() {
Utilities.showDLog(Tag, "upload failed");
disconnectFTP();
outputCode = FTPOutputCodes.FAILED;
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
Utilities.showDLog(Tag, "upload completed");
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "upload aborted");
}
});
} else if (supported) { // resume file upload
ftp.upload(new java.io.File(file_path), fileSize, new FTPDataTransferListener() {
#Override
public void transferred(int arg0) {
Utilities.showDLog(Tag, "Resume data transfered: " + arg0);
}
#Override
public void started() {
Utilities.showDLog(Tag, "Resume started");
}
#Override
public void failed() {
outputCode = FTPOutputCodes.FAILED;
disconnectFTP();
Utilities.showDLog(Tag, "Resume failed");
}
#Override
public void completed() {
outputCode = FTPOutputCodes.SUCCESSFULLY_UPLOADED;
}
#Override
public void aborted() {
outputCode = FTPOutputCodes.ABORTED;
disconnectFTP();
Utilities.showDLog(Tag, "resume aborted");
}
});
}
return outputCode;
}
protected void disconnectFTP() {
try {
ftp.disconnect(true);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
e.printStackTrace();
} catch (FTPException e) {
e.printStackTrace();
}
}

Loop to to check bluetooth adapter if it is unenable

Thanks all.
I work with bluetooth low energy android. In service I want to check if bluetoothadapter is enable or not. If not,after every 1 minute i continue to check. If it is enable I break and do some thing.
I know how to check but I do not know how to loop and break.
Thanks
In your service you can create an AsyncTask, and inside create the loop:
private class Task extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... arg0)
{
while (true)
{
if()
{
//it's enabled
break;
}
else
{
//it's disabled
}
Thread.sleep(60000);//millisecond to wait
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}//end background
#Override
protected void onPostExecute(String result)
{
}
}

unable to see toast inside oncreate

import android.widget.Toast;
public class Security extends MainActivity {
Socket sock,sock1;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.security);
new Thread(new Runnable()
{
public void run()
{
try{
sock=new Socket(ip,port1);
BufferedReader br=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String a=br.readLine();
Thread.sleep(2500);
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}
}
Not able to view toast when Security started. I dont know why? it is like that it should be wit in oncliklistener.?
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
});
You can only show toasts in the main UI thread.
If you need to do things on the UI thread from a background thread, have a look at runOnUiThread().

Android signin with Google plus issue on the first login

I implemented signin with google with no problems. I am using a fragment in place of an activity.
Testing the code on samsung galaxies it happens that signin system goes idle and do not call onConnected method.
This happens just the first time, when the terms and conditions shows.
Any advice?
Here is my code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initGoogle()
}
private void initGoogle() {
mPlusClient = new PlusClient.Builder(getActivity() , this , this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
}
public void connectWithPlus() {
launchProgressScreen();
if(mPlusClient != null && !mPlusClient.isConnected()){
mPlusClient.connect();
}else{
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR) {
mConnectionResult = null;
connectWithPlus();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result!= null && result.hasResolution()) {
try {
result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
connectWithPlus();
}
mConnectionResult = result;
}else{
onTaskResult(ProgressAlert.TASK_CANCEL_GOOGLE_LOGIN, null);
}
}
#Override
public void onConnected(Bundle connectionHint) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
#Override
protected String doInBackground(Object... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(getActivity(), mPlusClient.getAccountName(),
"oauth2:" + Scopes.PLUS_LOGIN );
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token){
getAuthDelegate().setToken(token, SocialAccount.google);
getAuthDelegate().loginUsingGoogle(token, new HashMap<String, String>());
}
};
task.execute();
}
#Override
public void onDisconnected() {
Log.w("Google Login", "called disconnected");
}
#Override
public void onClick(View v) {
connectWithPlus();
}
I faced same problem and I fixed it by overriding onResume method in Fragment.
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mGoogleApiClient.connect();
}
I am still not sure if its valid solution or not.
Thanks,
Rahul
You should process this catch block:
catch (UserRecoverableAuthException userRecoverableException) {
startActivity(userRecoverableException.getIntent());
}

Delay super.onbackpressed in android

I made a script which detects if there's internet connection:
public static boolean isOnline() {
try {
InetAddress.getByName("google.hu").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
If there's no internet the app will warn the user and the quit! But how to delay super.onBackPressed for 20 seconds? :)
this.toast1 = new Toast(getApplicationContext());
toast1.setGravity(Gravity.CENTER, 0, 0);
toast1.setDuration(20000);
toast1.setView(layout);
toast1.show();
super.onBackPressed();
Thread delayThread= new Thread(new Runnable()
{
#Override
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
activityInstance.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
super.onBackPressed();
}
});
}
});
delayThread.start();
The easiest is to create a Handler in onCreate()and use postDelayed() with a Runnable that calls super.onBackPressed()

Categories

Resources