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;
}
}
Related
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
MainActivity.java:
package com.trial_test.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import java.net.InetAddress;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
if (isNetworkConnected()) {
boolean is_test = isInternetAvailable();
if (isInternetAvailable()) {
// REMOTE RESOURCE
mWebView.loadUrl("https://example.com");
} else {
// LOCAL RESOURCE
mWebView.loadUrl("file:///android_asset/index.html");
}
} else {
// LOCAL RESOURCE
mWebView.loadUrl("file:///android_asset/index.html");
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
}
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
Trying to build / test an android WebView app with online & offline features.
But it always load offline page even when internet connection is available.
files
This was not enough to check internet connection,
You may try this
public class NetworkState {
public Boolean isNetworkAvailable(Context context) {
if (context == null)
return false;
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return true;
}
}
} else {
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
// Log.i("update_statut", "Network is available : true")
return true;
}
} catch ( Exception e) {
}
}
Log.e("update_statut", "Network is available : FALSE ");
return false;
}
}
Then Check your connection
NetworkState networkState =new NetworkState();
if (networkState.isNetworkAvailable(this)) {
//You are online
}else{
//You are offline
}
I'm trying to use Google Translation API but I'm getting not null pointer error, this is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.speakingtranslator.GoogleTranslateActivity.translte(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.speakingtranslator.MainActivity.translated(MainActivity.java:332)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:310)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:271)
Here is the code
public void translated() {
String translatetotagalog = editText.getText().toString();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
Log.v("translated text", text);
editTranslate.setText(text);
}
Here is the translte
String translte(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key="+ key +"&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Complete MainActivity.java
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
GoogleTranslateActivity translator;
private TextToSpeech textToSpeech;
private Button btn, button2, trans;
String soundName;
MediaPlayer mp = null;
String text2speak;
private boolean connected;
private static final String API_KEY = "API_KEY";
private EditText editText, editTranslate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
btn = findViewById(R.id.material_icon_button);
button2 = findViewById(R.id.material_icon_yoruba);
trans = findViewById(R.id.material_icon_translate);
checkPermission();
editText = findViewById(R.id.editText);
editTranslate = findViewById(R.id.editTranslate);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.US);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language is not supported!");
} else {
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
} else {
Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = editText.getText().toString();
Log.i("TTS", "button clicked: " + data);
int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speechStatus == TextToSpeech.ERROR) {
Log.e("TTS", "Error in converting Text to Speech!");
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
soundName = editTranslate.getText().toString();
soundName = soundName.replaceAll("\\s+", "_").toLowerCase();
SoundManager(soundName);
Toast.makeText(getApplicationContext(), soundName, Toast.LENGTH_LONG).show();
}
});
trans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
text2speak = editText.getText().toString();
new EnglishToTagalog().execute();
}
});
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.material_icon_mic).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("Listening...");
break;
}
return false;
}
});
//Initialize and Assign Variable
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//Set Home Selected
bottomNavigationView.setSelectedItemId(R.id.home);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.messages:
startActivity(new Intent(getApplicationContext(),Messages.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
protected void onError(Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
translator = new GoogleTranslateActivity(API_KEY);
Thread.sleep(15000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
// start the progress dialog
progress = ProgressDialog.show(MainActivity.this, null,
"Translating...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
translated();
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void translated() {
String translatetotagalog = editText.getText().toString();
Toast.makeText(getApplicationContext(), translatetotagalog, Toast.LENGTH_LONG).show();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
//translatabletext = (TextView) findViewById(R.id.translatabletext);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
Log.v("translated text", text);
editTranslate.setText(text);
}
protected void SoundManager(String sn){
if (mp != null){
mp.reset();
mp.release();
}
switch (sn){
case "e_kaaro":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaaro);
break;
case "e_kaasan":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaasan);
break;
case "e_kaale":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaale);
break;
case "bawo_ni_o_se_n_se":
mp = MediaPlayer.create(getApplicationContext(), R.raw.bawo_ni_o_se_n_se);
break;
case "mo_nife_re":
mp = MediaPlayer.create(getApplicationContext(), R.raw.mo_nife_re);
break;
default:
mp = MediaPlayer.create(getApplicationContext(), R.raw.crowd);
}
//Toast.makeText(getApplicationContext(), "clicked " + sn, Toast.LENGTH_LONG).show();
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
public boolean checkInternetConnection() {
//Check internet connection:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//Means that we are connected to a network (mobile or wi-fi)
connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
return connected;
}
}
I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class bleutoothrevivedeletenow extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
Button StartConnection;
Button Disconnect;
Button Recieve;
TextView incomingData;
InputStream mmInStream = null;
String incomingMessage;
StringBuilder messages;
Thread ListenInput = new Thread() {
#Override
public void run() {
try {
mmInStream = btSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
while (true) {
// Read from the InputStream
try {
if (mmInStream == null) {
Log.e("", "InputStream is null");
}
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
messages.append(incomingMessage);
Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
//TODO Remove this
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
}
}
};
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bleutoothrevivedeletenow);
messages = new StringBuilder();
SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
address = sharedPreferences.getString("ADDRESS", "");
StartConnection = findViewById(R.id.button5);
Disconnect = findViewById(R.id.button6);
incomingData = findViewById(R.id.textView);
Recieve = findViewById(R.id.button7);
StartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConnectBT().execute();
}
});
Disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btSocket != null) //If the btSocket is busy
{
try {
btSocket.close(); //close connection
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
}
});
Recieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListenInput.start();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
incomingData.setText(messages);
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
});
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
}
}
}
P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data
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 !!");
}
}
}
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;
}