I am trying to approach a problem in which I have to disable and then enable mobile data with some delay in between (reset mobile data 2G).
step 1: disable mobile data
step 2: wait till mobile data gets disabled
step 3: some delay say 2 seconds
step 4: enable mobile data
step 5: wait till mobile data gets enabled
step 6: continue with the program.....
doing some research I came up with this...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!mobileDataEnabled(getApplicationContext())){
setMobileDataEnabled(getApplicationContext(),true);
Toast.makeText(getApplicationContext(), "ENABLED", Toast.LENGTH_SHORT).show();
}else{
setMobileDataEnabled(getApplicationContext(),false);
Toast.makeText(getApplicationContext(), "DISABLED", Toast.LENGTH_SHORT).show();
}
}
});
}
//the method below enables/disables mobile data depending on the Boolean 'enabled' parameter.
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass = null;
try {
conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// below method returns true if mobile data is on and vice versa
private boolean mobileDataEnabled(Context context){
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
return mobileDataEnabled;
}
The above code will turn on/off mobile data but it happens really quick. this quick that the mobile data doesn't even turn off actually. how do I add a delay in between and achieve the steps I mentioned above? any help would be appreciated.
thanks!
Just put
Thread.sleep(1000);
in between the code statements (before setMobileData APIs) to achieve delay. The delay parameter is in milliseconds. So change it according to your requirement.
EDIT: Try putting the delay into a handler, using this code:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Whatever you want to do
}
}, 1000);
Try this may work. Use your code for turning off/on your packet data.
You should use a broadcast receiver for getting the events of connectivity.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
Check the below link for details
Get notified on connectivity change
public void mobiledataenable(boolean enabled) {
try {
final ConnectivityManager conman = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try (this will turn the data off then wait till it's off then on again):
setMobileDataEnabled(getApplicationContext(),false);
while(mobileDataEnabled(getApplicationContext()){
//Just wait, don't do anything
}
//Turn it on here
setMobileDataEnabled(getApplicationContext(),true);
Lemme know if i couldn't get you properly!
// first check whether it is on\off...
public void setMobileDataEnabled(Context context, boolean status) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
{
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, status);
}
Related
I am trying to play audio in my app from parse.com. I'm able to start and play the Media file but cant pause and stop it. Here is the code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Table");
query.getInBackground(ObjId, new GetCallback<ParseObject>() {
public void done(ParseObject recording, com.parse.ParseException e) {
if (e != null) {
//do nothing
}
else {
ParseFile audioFile = recording.getParseFile("Audio");
String audioFileURL = audioFile.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
//mediaPlayer.start();
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
You're not playing a live stream, the file plays after the object is downloaded as you're setting up the action inside the
public void done(ParseObject recording, com.parse.ParseException e)
and this method is executed in another thread which complicates the situation a a lot, you should get the file first with:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Table");
ParseObject obj = query.getFirst()
ParseFile audioFile = obj.getParseFile("Audio");
String audioFileURL = audioFile.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
And then implement your other features.
I am trying to connect one android device to another using wifi. One device is acting as a server using hotspot. Another device is connected to it. But when I am running the following piece of code, it gives the following exception.
java.net.ConnectException: failed to connect to /192.168.43.198 (port 5555): connect failed: ENETUNREACH (Network is unreachable)
I am using the below files.
HostActivity.java
public class HostActivity extends Activity {
ListView lvHost;
HostAdapter adHost;
final String HostTAG = "Host1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
WifiManager wifiManager = (WifiManager)this.getSystemService (Context.WIFI_SERVICE);
new RetrieveFeedTask2(getApplicationContext()).execute("");
int i =0 ;
lvHost = (ListView) findViewById( R.id.lvHost);
int j = 0;
ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
adHost = new HostAdapter(list,this);
lvHost.setAdapter(adHost);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.host, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class RetrieveFeedTask2 extends AsyncTask<String, Context, String> {
Context ctx = null;
public RetrieveFeedTask2(Context Dctx) {
// TODO Auto-generated constructor stub
ctx = Dctx;
}
protected String doInBackground(String ...url) {
final String HostTAG = "Host1";
final WifiManager wifiManager = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
try {
Boolean end = false;
Log.i("test","HostRun");
ServerSocket ss = new ServerSocket(5555);
while(!end){
Log.i("test", "HostRun2");
//Server is waiting for client here, if needed
Socket s = ss.accept();
Log.i("test", "HostRun3");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
Log.i("test", "From client: "+st);
System.out.println("From client: "+st);
//output.println("Good bye and thanks for all the fish :)");
s.close();
// ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.i("test","host unknown");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
ClientActivity.java
public class ClientActivity extends Activity {
final String ClientTAG = "Client1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
WifiManager wifiManager = (WifiManager)getSystemService("wifi");
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = Formatter.formatIpAddress(ipAddress);
new RetrieveFeedTask().execute(ip);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
//Context context;
protected String doInBackground(String ...urls) {
final String ClientTAG = "Client1";
InetAddress ia=null;
Log.i("test", "ClientRun1");
try {
try {
ia=InetAddress.getLocalHost();
Log.i("test",ia.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Socket s = new Socket("192.168.43.198",5555);
Log.i("test", "ClientRun");
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
//. . .
//Close connection
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
I tried googling. Many have mentioned same problem and I tried all the solutions but still not able to connect. Please help.
Some suggestions:
Use 10000 < port number <= 65536 in android. (less than 10000,
some errors may occur).
If the mobile network is active, the ServerSocket(port number) uses the outgoing IP (mobile network's IP). Try ServerSocket(int port, int backlog, InetAddress localAddress) instead.(You need to specify an address, that is, hotspot's address.)
In ClientActivity.java, I see you pass an IP through execute(ip), but you didn't use it. You can do Socket s = new Socket(ip,5555);.
AsyncTask is not recommended for doing a long time work. Use Thread instead.
I'm trying to establish a Bluetooth connection in Android 4.4 but the connect method of BluetoothSocket seems to be working strangely. My app can assume the device is already bonded, so I can connect via MAC address. The thing is that it connects perfectly and immediately the first time the device is bonded, but if I relaunch it, the connection isn't established and a timeout occurs. I do this inside a while loop until it connects, but it takes too long for a real solution or it doesn't work at all. Here's a sample of my code:
public class BluetoothManager{
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket socket;
private OutputStream output;
private InputStream input;
public BluetoothManager() {
/***************/
/* Constructor */
/***************/
// lock = new Object();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public boolean turnOnBluetooth() {
/**************************************/
/* Turn on Bluetooth an notify result */
/**************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// enable Bluetooth if not enabled yet
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
while (!bluetoothAdapter.isEnabled()) {
Log.i("Debug", "Waiting for bluetooth to turn on");
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean turnOffBluetooth() {
/***************************************/
/* Turn off Bluetooth an notify result */
/***************************************/
// check if bluetooth is supported
if (bluetoothAdapter == null) {
return (false);
} else {
// disable Bluetooth if not enabled yet
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
while (bluetoothAdapter.isEnabled()) {
Log.i("Debug
Thread.sleep(500);
} catch (Exception e) {
}
}
return (true);
}
}
public boolean configureBluetooth(String MACaddress) {
/***********************************************************************/
/* Configures to the specified bluetooth device and returns the result */
/***********************************************************************/
Log.i("Debug", "Connecting to Bluetooth Device");
bluetoothDevice = bluetoothAdapter.getRemoteDevice(MACaddress);
return (true);
}
#SuppressLint("NewApi")
public void createSocket() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
final UUID serialUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = null;
output = null;
input = null;
Method m = bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket)m.invoke(bluetoothDevice, 1);
}
#SuppressLint("NewApi")
public void connect() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
/************************************/
/* Connects to the bluetooth device */
/************************************/
Log.i("Debug", "en connect");
while (!socket.isConnected()) { // we try until the connection is established
try {
socket.connect();
output = socket.getOutputStream();
input = socket.getInputStream();
} catch (IOException e) {
Log.i("Depuración", "Connection not established. Another run : "+e);
try {
Thread.sleep(1000);
} catch (Exception e1) {
}
}
}
}
public void terminateConnection() throws IOException {
Log.i("Debug", "terminating connection");
if(output!=null){
Log.i("Debug", "output!=null - stop streaming");
stopStreaming();
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
if(input!=null){
Log.i("Debug", "input!=null");
input.close();
input=null;
}
if(output!=null){
Log.i("Depuración", "output!=null");
output.close();
output = null;
}
if(socket!=null){
Log.i("Debug", "socket!=null");
socket.close();
socket=null;
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
turnOffBluetooth();
try {
Thread.sleep(100);
} catch (Exception e) {
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.gc();
}
If I call this methods from my MainActivity, it works, but only the first time the device is bonded. If I launch the app again I get an exception trying to connect to the device in:
socket.connect();
I suspect it has something to do with the way I terminate the connection, but I can't figure it out. Here's the sequential call of the methods:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = new BluetoothManager();
try {
bluetoothManager.terminateConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
bluetoothManager.turnOffBluetooth();
bluetoothManager.turnOnBluetooth();
boolean configured = false;
while (!configured) {
Log.i("Debug", "Configuration Attemp");
configured = bluetoothManager.configureBluetooth(MACaddress);
}
Log.i("Debug", "Bluetooth Configured");
try {
bluetoothManager.createSocket();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("Depuración", "Socket created");
try {
bluetoothManager.connect();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Debug", "Connected!!!!");
protected void onPause() {
Log.i("Debug", "On pause");
// TODO Auto-generated method stub
try {
bluetoothManager.terminateConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothManager = null;
System.gc();
super.onPause();
};
I've been trying to solve this for days and I still can't find a reason.
Well I'm not a Pro on this, but it looks like you should call bluetoothManager.terminateConnection(); when app is closing, lets say onDestroy, but not onCreate; I also had problems to connect, if previous connection was not terminated correctly. just try add this method to your main activity:
#Override
public void onDestroy(){
if (bluetoothManager != null){
bluetoothManager.terminateConnection();
}
super.onDestroy();
}
hope that helps.
So I'm making an Android soundboard app and get this exception and my app crashes when I click the last button of the soundboard app.
[THE CODE]
public class newBoard extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11,
R.id.button12, R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17, R.id.button18,
R.id.button19, R.id.button20, R.id.button21, R.id.button22,
R.id.button23, R.id.button24, R.id.button25, R.id.button26,
R.id.button27, R.id.button28, R.id.button29, R.id.button30,
R.id.button31, R.id.button32 };
final int[] soundIds = { R.raw.bengalka, R.raw.cista_psihologija,
R.raw.da_ne, R.raw.dejo_narkomane, R.raw.dizi_se,
R.raw.fejslifting, R.raw.fotomale, R.raw.gladan_sam,
R.raw.jasna_pero, R.raw.jeben_vam_mater, R.raw.kae_ivanisevic,
R.raw.kae_to_fora, R.raw.kaj_gledas, R.raw.kaj_vi_gledate,
R.raw.kineza_crnaca, R.raw.kozo_nepodojena, R.raw.marino,
R.raw.mater_zbrgljavu, R.raw.muha, R.raw.nema_papira,
R.raw.nered, R.raw.ne_spominji_majku, R.raw.nisam_se_uroko,
R.raw.odfurati_doktoru, R.raw.pljacka, R.raw.pusi_ke,
R.raw.sava_sava, R.raw.tebe_i_magazin, R.raw.tog_vani_nema,
R.raw.za_dom_spremni, R.raw.zrigati };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The exception shows on this line:
selectedSoundId = soundIds[i];
selectedSoundId = soundIds[i];
final int[] buttonIds = 33 Value - you have two R.id.button16 in your buttonIds
final int[] soundIds = 31 Value
So it is crash.
Off-by-two: There are 33 button ids and 31 sound ids. Button 16 is duplicated.
For mapping resource ids and other integers, consider a map, such as SparseIntArray.
This question already has answers here:
Android check internet connection [duplicate]
(20 answers)
Closed 8 years ago.
I am creating android app that call rest services made by me on server and server is ruuning live but due to internet connectivity issues some time my application runs successfully but sometime it crashes. The code for my connection class is as
public class CommunicationClass {
#SuppressWarnings("unused")
private static final String TAG = null;
public String Domain;
public HttpClient client;
public HttpPost datapost;
public HttpResponse response;
public BufferedReader reader;
public StringBuilder builder;
public JSONTokener tokener;
public JSONObject finalResult;
List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(10);
public void setClient() {
// TODO Auto-generated method stub
client = new DefaultHttpClient();
System.out.println("Created http client");
}
public void setDomain(String st) {
// TODO Auto-generated method stub
Domain = st;
System.out.println("Domain has been set");
}
public void setResponse(){
response=null;
System.out.println("Response has been initalized by null");
}
public void setStringBuilder(){
builder = new StringBuilder();
}
public void setreader(){
try {
reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), "UTF-8"));
System.out.println("Setting the contents of the Reader");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("In the UnsupportedEncodingException catch of the Reader");
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
System.out.println("In the IllegalStateException catch of the Reader");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("In the IOException catch of the Reader");
e.printStackTrace();
}
}
public void startpost(String str){
datapost=new HttpPost(str);
System.out.println("Created the httppost domain");
}
public void insertdata(String tag,String value){
namevaluepairs.add(new BasicNameValuePair(tag,value));
System.out.println("Added the parameter "+tag);
}
public void trydata(){
try {
this.datapost.setEntity(new UrlEncodedFormEntity(this.namevaluepairs));
System.out.println("Setting the entity");
try {
this.response = this.client.execute(this.datapost);
System.out.println("executing the client");
if(this.response != null){
System.out.println("i am in if of this.response!=null");
}
else{
System.out.println("i am in else of this.response!=null");
}
System.out.println("in response try box");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("in ClientProtocolException Catch box");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("in IOException Catch box");
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("in UnSupported Catch box");
e.printStackTrace();
}
}
public void readresponse(){
try {
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
System.out.println(this.builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokener = new JSONTokener(builder.toString());
try {
finalResult = new JSONObject(tokener);
System.out.println("I am in try block of json final result reading");
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("I catch block of jsonException");
e.printStackTrace();
}
}
}
it gives me error on line trydata(); that actually execute the HTTP Client so i want to make sure that it should not crash due to internet connectivity but may throw the exception that can be caught or make toast. Guys need help on this
Thanks!
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
and dont forgett:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
it's work great for me.
Check Internet connectivity before calling Webservice:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Although other answers are correct, they are partially correct. If you want ot know you have internet connection, not just connected to a wi-fi hotspot, you have to ping a site. This is something I found yesterday, and works if you are connected but have no internet connection via this hotspot. Basically it pings google. Use a boolean with it, and put it in the checks in the other people's answers' check.
Use this:
public static Boolean checkForInternetConnection(Context context) {
final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
} else {
return false;
}
}