i got an error when i just open my app.. on the first screen it show splash activity ... and there's an error
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
and this one the code on my splash activity, dunno on what section it got warn..
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.xxx.xx.helper.SessionManager;
import com.xxx.xx.util.ConnectionDetector;
public class Splash extends AppCompatActivity {
private ConnectionDetector cd;
Boolean isInternetPresent = false;
protected SessionManager session;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new SessionManager(getApplicationContext());
cd = new ConnectionDetector(getApplicationContext());
Thread timer = new Thread(){
public void run(){
try {
sleep(2000);
} catch (Exception e) {
e.printStackTrace();
} finally {
checking();
}
}
};
timer.start();
}
public void checking() {
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent) {
session.checkLogin();
finish();
} else {
alert.showAlertDialog(Splash.this, "No Connection", "Check Your Internet Connection.",false);
finish();
}
}
}
and this one my connection manager code ..
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
}
After trying and searching on stackoverflow for ways to solve internet connection error on android, I found nothing what works for me. I tryed the code you can see at the bottom but it wont works for internet connection error. mWebView.loadUrl("file:///android_asset/myerrorpage.html"); become executed every time when the url in the browser isnt http://192./loc/index.php. When I have a redirecting at index.php the error file become showed. How can I change that, or know anyone a code that check the internet connection availability and then do something?
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
} else {
return true;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_localy);
mWebView = (WebView) findViewById(R.id.webview);
// Brower niceties -- pinch / zoom, follow links in place
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new GeoWebViewClient());
// Below required for geolocation
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.setWebChromeClient(new GeoWebChromeClient());
// Load google.com
mWebView.loadUrl("http://192./loc/index.php");
}
}
} catch (Exception e) {
return false;
}
}
Your question isn't very clear.
If you need check connection you need:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Then if need check for real internet connection you can try something like this:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
And add the ACCESS_NETWORK_STATE permission to the manifest.
This question already has answers here:
Detect network connection type on Android
(14 answers)
Closed 7 years ago.
I am using the following code for checking if internet connection available or not , this code works well if wifi or data disabled from mobile but problem is that this code hangs mobile when data is not receive during internet connected....
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
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;
}
}
<!--Constants.INTERNET_CONNECTION_URL="YOUR_WEB_SERVICE_URL/URL OF GOOGLE";-->
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.vgheater.util.Constants;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class CheckConnectivity {
private Context _context;
public CheckConnectivity(Context context) {
this._context = context;
}
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;
}
public boolean hasActiveInternetConnection() {
if (isConnectingToInternet()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(Constants.INTERNET_CONNECTION_URL).openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(5000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return false;
}
} else {
return false;
}
}
}
You can use it as follows..
private class InternetTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog internetDialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
internetDialog = new ProgressDialog(RegisterUser.this);
internetDialog.setCancelable(false);
internetDialog.setCanceledOnTouchOutside(false);
internetDialog.setMessage(Html.fromHtml("<font color='#616161'>Checking Internet Connectivity.</font>"));
internetDialog.show();
}
protected Boolean doInBackground(String... urls) {
boolean response = false;
try {
response = checkConnectivity.hasActiveInternetConnection();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(Boolean result) {
internetDialog.dismiss();
if (result) {
//do stuff
} else {
new ShowToast(RegisterUser.this, "Connect to Internet & Try Again !!");
}
}
}
on Signin Button click I am performing the active internet connection check. But the Visibility is not working for the layout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
bar = (ProgressBar) this.findViewById(R.id.progressBar);
linearlayout = (LinearLayout) findViewById(R.id.SignInLinearLayout);
signin = (Button) findViewById(R.id.btn_signin);
user_name = (EditText) findViewById(R.id.Txt_Signin_Email);
user_password = (EditText) findViewById(R.id.Txt_signIn_Password);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearlayout.setVisibility(View.GONE);
bar.setVisibility(View.VISIBLE);
if (CommonFunctions.hasActiveInternetConnection(getBaseContext())) {
params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("username", user_name.getText().toString()));
params.add(new BasicNameValuePair("password", user_password.getText().toString()));
// Calling async task to get json
new GetLogIn_Details().execute();
} else {
bar.setVisibility(View.GONE);
linearlayout.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Network Not Available... \n Please check Your Wifi Connection or Mobile Network", Toast.LENGTH_LONG).show();
}
}
}
);
}
Here is the network check code
public abstract class CommonFunctions {
private static String LOG_TAG = "Network Message";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
Boolean aResultM = isOnline();
return aResultM;
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Context _context) {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public static Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
The visibility is not working. But if i remove the network check code from the click event the visibility is working. How can i solve this issue. I found some hints like using delay method.But I don't want to use delay or timer method.Because the network check method itself take some time to execute.
I am building an application which does some work when a specific wifi network is connected. To check if my wifi network is connected i am running a background service which runs a thread of infinite loop inside it. The thread checks for wifi connection is active or not. If yes, then it displays the notification and keeps the notification until wifi is disconnected. I cannot find the better approach to check for my connection asynchronously. The problems I am facing is as follows:
If service is already running and I connect to network i get a notification. Now I open my application and notification still shows. Then I disconnect from wifi connection and the notification disappears, I connect again and notification appears again as well ,as it should. Now if I remove my app from the overview and then disconnect from the wifi, my notification does not go, it sticks in the notification panel. Although this error is uncertain and occur in some phones and not in some.
I am posting my service code and main activity code.
Please suggest me a better approach to do this task.
MyService.java
package com.sumatone.volsbbonetouch;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Created by shalini on 31-01-2015.
*/
public class MyService extends Service {
private boolean CHECK=true,tcheck=true;
private Thread t1;
#Override
public void onCreate() {
super.onCreate();
final ShowNotification s=new ShowNotification(this);
//Toast.makeText(this,"Service was created",Toast.LENGTH_SHORT).show();
t1=new Thread(new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CHECK=checkConnection();
if (CHECK==true&&tcheck==true) {
Log.d("status", "connected");
s.notifyInstant();
tcheck=false;
}
else if (CHECK==false&&tcheck==false) {
Log.d("status", "disconnected");
s.remove();
tcheck=true;
}
}
}
});
/*t2=new Thread(new Runnable() {
#Override
public void run() {
while(true) {
checkConnection();
if (!CHECK) {
Log.d("status", "disconnected");
t1.notify();
try {
t2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});*/
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(this,"Service was started",Toast.LENGTH_SHORT).show();
t1.start();
return super.onStartCommand(intent,flags,startId);
}
public boolean checkConnection() {
/*final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected())
{
Log.d("wifi",wifi.getExtraInfo());
if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}*/
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiManager.isWifiEnabled())
{
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
final SupplicantState supp= wifiInfo.getSupplicantState();
Log.d("wifi",wifiInfo.getSSID());
if((wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")||wifiInfo.getSSID().equalsIgnoreCase("\"VOLS\""))&&wifi.isConnected()) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}
}
#Override
public void onDestroy() {
//Toast.makeText(this,"Service was destroyed",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.sumatone.volsbbonetouch;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
/**
* Created by shalini on 29-01-2015.
*/
public class MainActivity extends Activity implements View.OnClickListener {
private String url="http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
EditText uname,password;
TextView res;
Button login,logout,slogin;
List<NameValuePair> details;
ProgressDialog pDialog;
SharedPreferences s;
Authentication a;
String u,p,toasttext,session;
ImageView about;
String service="ProntoAuthentication";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isMyServiceRunning(MyService.class))
startService(new Intent(this,MyService.class));
about=(ImageView)findViewById(R.id.about);
uname=(EditText)findViewById(R.id.user);
password=(EditText)findViewById(R.id.pass);
s= PreferenceManager.getDefaultSharedPreferences(this);
uname.setText(s.getString("prontousername",null));
password.setText(s.getString("prontopassword",null));
a= new Authentication(this);
login=(Button)findViewById(R.id.login);
logout=(Button)findViewById(R.id.logout);
slogin=(Button)findViewById(R.id.savelogin);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(this);
logout.setOnClickListener(this);
slogin.setOnClickListener(this);
about.setOnClickListener(this);
session=s.getString("session","first");
if(session.equals("first")){
about.performClick();
SharedPreferences.Editor editor=s.edit();
editor.putString("session","used");
editor.commit();
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login) {
if(checkConnection()) {
details = new ArrayList<NameValuePair>();
url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
u = uname.getText().toString();
p = password.getText().toString();
details.add(new BasicNameValuePair("userId", u));
details.add(new BasicNameValuePair("password", p));
details.add(new BasicNameValuePair("serviceName", service));
new GetEvents().execute();
}
else
Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.logout) {
if(checkConnection()) {
details = null;
url = "http://phc.prontonetworks.com/cgi-bin/authlogout";
new GetEvents().execute();
}
else
Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.savelogin) {
if (checkConnection()) {
details = new ArrayList<NameValuePair>();
url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
u = uname.getText().toString();
p = password.getText().toString();
SharedPreferences.Editor editor = s.edit();
editor.putString("prontousername", u);
editor.putString("prontopassword", p);
editor.commit();
details.add(new BasicNameValuePair("userId", u));
details.add(new BasicNameValuePair("password", p));
details.add(new BasicNameValuePair("serviceName", service));
new GetEvents().execute();
} else
Toast.makeText(this, "Not connected to Volsbb", Toast.LENGTH_SHORT).show();
}
if(v.getId()==R.id.about)
{
Intent i= new Intent(this,AboutDialog.class);
startActivity(i);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public boolean checkConnection() {
/*final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected())
{
Log.d("wifi",wifi.getExtraInfo());
if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}*/
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
Log.d("wifi",wifiInfo.getSSID());
if(wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}
}
private class GetEvents extends AsyncTask<Void, Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Processing");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String valresponse = sh.makeServiceCall(url, ServiceHandler.POST,details);
Log.d("Response: ", ">" + valresponse);
return valresponse;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if(result.contains("Logout successful"))
toasttext="Logged out";
else if(result.contains("Successful Pronto Authentication"))
toasttext="Logged in";
else if(result.contains("There is no active session to logout"))
toasttext="There is no active session";
else if(result.contains("Sorry, please check your username and password"))
toasttext="Invalid username/password";
else if(result.contains("Sorry, your free access quota is over"))
toasttext="Your free access qouta is over";
else
toasttext="Already Logged in";
Toast.makeText(getApplicationContext(),toasttext,Toast.LENGTH_SHORT).show();
}
}
}
You must return START_STICKY in onStartCommand() to keep the service running. START_STICKY tells the OS to recreate the service if it is killed for some reason (i.e., memory, manually killing the app).
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//Your service code
return START_STICKY;
}