我有一个与Lan Adapter连接的android设备,它非常随机地失去了连接。因此,它需要我重新启动网络或重新启动整个设备才能使其恢复工作。当我失去网络连接时,如何编程运行Android应用程序以重新启动网络((如果可能,请重新启动Lan适配器或网络,否则请重新启动设备))。
例如,在Linux中,我们使用ifup和ifdown
You will need to use broadcast receiver. You will continuously receive updates in connectivity.(Connected/Disconnected)
Example:
Manifest:
Permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Register broadcast receiver:
<receiver android:name=".ConnectivityChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Create receiver class:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that which service class will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
YourService.class.getName());
intent.putExtra("isNetworkConnected",isConnected(context));
startService(context, (intent.setComponent(comp)));
}
public boolean isConnected(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}
}
Your service class:
class YourService extends IntentService{
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
// your code
}
}