I made an Android application that is used to exchange files with a pc.
The computer and the device are connected to the same network and everything worked very well.
But since I put a 4g sim card, the transfer is no longer done, does anyone know how to solve this problem?
There must be a way to force my application to use only ethernet connection?
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
How I check connection:
public static Boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
boolean isEthernet = false;
if (activeNetwork != null) {
isEthernet = activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET;
}
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting() && isEthernet;
}
Main function:
public void sendFilesInFolder(Boolean bool) {
if (isConnected(MainActivity.this)) {
ProgressBar progressBar;
if (bool) progressBar = mProgressBarD;
else progressBar = mProgressBarM;
fileSender = new FileSender(prefs.getString("ip_adress", null),
Integer.valueOf(prefs.getString("port_dest", null)),
bool, colisageBase, progressBar);
fileSender.execute();
} else {
Toast.makeText(MainActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}
Related
I have been trying to use a custom Image that is to be shown to a user when he is offline and when the user clicks on the image, the activity should be reloaded.
P.s I am using Blogger API
first add this permission to manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
thin in your activty
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
and use like this
if(isNetworkAvailable()){
//internt connect
}else{
// no network
//you can show image here by adding layout and set visibility gone and when no connection set visible
}
You can use Custom Dialog of full Screen to check for internet. So, you can write,
if(isNetworkAvailable()){
//Your Logic for Internet Connection
}else {
val noInternetDialog = Dialog(this, android.R.style.Theme)
noInternetDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
noInternetDialog.setContentView(R.layout.no_internet_layout)
val window = noInternetDialog.window
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
// What ever you have widget, can use them here.
//for example
val button_try_again = noInternetDialog.findViewById(R.id.buttonId)
val image_to_display = noInternetDialog.findViewById(R.id.imageId)
// listeners for image
noInternetDialog.show
}
isNetworkAvaibale() is,
fun isNetworkAvailable(): Boolean {
val connectivityManager = ApplicationInit.getAppContext()
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
PS : Do not forget to add Internet Permissions
For my app, I was trying to detect when the user is connected to the internet. This is one of the methods I've been using, although I've used some other that where basically the same, but using other methods of the objects used:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
return false;
}
Even if this does not lead to any compilation error, when launching the app it stops abruptly and does not respond. I'd like to know why this happens and how to solve it or, if has no aparent solution, if there's another way of doing what I wanted.
I have tried deleting part of the code strategically and I have noticed that the part that gives problems is netInfowith both of ways it is being used, but I don`t know why.
Add Access Network Permission in AndroidManifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
First add users-permission in AndroidManifest.xml file like this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Second, this pics of code can give you a boolean. Network connection is available or not. so put it in a method and get return of those code like this..
public boolean getCheckedNetStatus(Context context) {
try{
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}catch(Exception e){
Log.e("Net Check Err", e.toString());
return false;
}
}
Have try catch will protect your from unexpected crash your app...
Now Call it to conditionally execute your certain action like this
if(getCheckedNetStatus(yourActivity.this)){
//Net is available
//So do your action
}else{
//Net not available
//you can notify user that net not available
//So you (User) can't do this
}
I want to check for particular update when user each time connects to internet.I tried the following codes :
unfortunately app is getting stopped while checking for network
Broadcast receiver for checking internet connection in android app
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Java
public class UpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
My problem is these codes only receive only once , If the user disconnect wifi and reconnects the BroadcastReceiver unable to notify.Any help is appreciated .
Once I had implemented a check in my app, to see if there is any internet connection or not. You can have a look at this --
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context cont){
this.context = cont;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
You can initialize an object of this class in your OnCreate method.
And finally call this class' method just before you upload files.
Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
//perform your job here.
}
EDITED::
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
Hope this helps.
I don't want my app to crash if the user doesn't have wifi or 3g connectivity. How can I catch this at runtime in my app?
First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device.
You'll need the ACCESS_NETWORK_STATE permission to use this service.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi.isConnected() == false && mMobile.isConnected() == false) {
showDialog(DIALOG_NETWORK_UNAVAILABLE);
}
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) is deprecated.
Below is an improved solution for the latest Android SDK.
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
boolean is3gEnabled = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connManager.getAllNetworks();
for(Network network: networks)
{
NetworkInfo info = connManager.getNetworkInfo(network);
if(info!=null) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
is3gEnabled = true;
break;
}
}
}
}
else
{
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mMobile!=null)
is3gEnabled = true;
}
I want to check when the network of phone in Android goes off. Can I capture that event?
I am not getting the proper API or any example which would explain the same. If anyone had done or any example links would be really helpful.
New java class:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
#Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
New xml in your AndroidManifest.xml under the "manifest" element:
<!-- Needed to check when the network connection changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
New xml in your AndroidManifest.xml under the "application" element:
<receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
I have been using a small setup to check the bandwidth for determining how to scale things, such as images.
Under the activity, in AndroidManifest:
<intent-filter>
...
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
In the activity where the checks are being performed:
boolean network;
int bandwidth;
#Override
public void onCreate(Bundle savedInstanceState) {
...
network = isDataConnected();
bandwidth = isHighBandwidth();
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
network = isDataConnected();
bandwidth = isHighBandwidth();
}
}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
...
}
...
private boolean isDataConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
private int isHighBandwidth() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getLinkSpeed();
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkType();
}
return 0;
}
An example usage would then be:
if (network) {
if (bandwidth > 16) {
// Code for large items
} else if (bandwidth <= 16 && bandwidth > 8) {
// Code for medium items
} else {
//Code for small items
}
} else {
//Code for disconnected
}
It's not the prettiest, but it allows enough flexibility that I can change the bandwidth cutoff for items depending on what they are and my requirements for them.
If using Android Annotations is an option for you try this in your activities - that's all, the rest is generated:
#Receiver(actions = ConnectivityManager.CONNECTIVITY_ACTION,
registerAt = Receiver.RegisterAt.OnResumeOnPause)
void onConnectivityChange() {
//react
}
Use this only if you already use AndroidAnnotations - putting this dependency inside your project only for this piece of code would be overkill.
The above answer only works if mobile packet data is enabled. Otherwise, ConnectivityManager would be null and you can no longer retrieve NetworkInfo. The way around it is to use a PhoneStateListener or TelephonyManager instead.