I am trying to build my first app for Android and, firstly, I compiled the example application in the networkusage.zip file on the Android Developers website (location: http://developer.android.com/training/basics/network-ops/index.html). It worked fine, so I tried to modify it according to my goal.
The modified code works fine when connects to a Wi-Fi network, but if I set it to any network it fails displaying the message: "Lost connection."
I modified only "NetworkActivity.java"
public class NetworkActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
private static final String URL ="http://www.kibao.org/simu/wap.php?lng=";
final Context context = this;
// Whether there is a Wi-Fi connection.
private static boolean wifiConnected = false;
// Whether there is a mobile connection.
private static boolean mobileConnected = false;
// Whether the display should be refreshed.
public static boolean refreshDisplay = true;
// The user's current network preference setting.
public static String sPref = null;
public static String pagina = "";
// The BroadcastReceiver that tracks network connectivity changes.
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register BroadcastReceiver to track connection changes.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
}
// Refreshes the display if the network connection and the
// pref settings allow it.
#Override
public void onStart() {
super.onStart();
// Gets the user's network preference settings
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Retrieves a string value for the preferences. The second parameter
// is the default value to use if a preference value is not found.
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
// Only loads the page if refreshDisplay is true. Otherwise, keeps previous
// display. For example, if the user has set "Wi-Fi only" in prefs and the
// device loses its Wi-Fi connection midway through the user using the app,
// you don't want to refresh the display--this would force the display of
// an error page instead of stackoverflow.com content.
if (refreshDisplay) {
loadPage();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
// Checks the network connection and sets the wifiConnected and mobileConnected
// variables accordingly.
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
// Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
// This avoids UI lock up. To prevent network operations from
// causing a delay that results in a poor user experience, always perform
// network operations on a separate thread from the UI.
private void loadPage() {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
// AsyncTask subclass
//new DownloadXmlTask().execute(URL);
String lng = getResources().getString(R.string.lng);
new DownloadWebpageTask().execute(URL.concat(lng));
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
setContentView(R.layout.main);
// The specified network connection is not available. Displays error message.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadData(getResources().getString(R.string.connection_error),
"text/html", null);
}
// Populates the activity's options menu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
// Handles the user's menu selection.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(settingsActivity);
return true;
case R.id.refresh:
loadPage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
/**
*
* This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION,
* which indicates a connection change. It checks whether the type is TYPE_WIFI.
* If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the
* main activity accordingly.
*
*/
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// Checks the user prefs and the network connection. Based on the result, decides
// whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// If device has its Wi-Fi connection, sets refreshDisplay
// to true. This causes the display to be refreshed when the user
// returns to the app.
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
// If the setting is ANY network and there is a network connection
// (which by process of elimination would be mobile), sets refreshDisplay to true.
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
// Otherwise, the app can't download content--either because there is no network
// connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
// is no Wi-Fi connection.
// Sets refreshDisplay to false.
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
// Implementation of AsyncTask used to download Webpage
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
// Displays the HTML string in the UI via a WebView
WebView myWebView = (WebView) findViewById(R.id.webview);
//myWebView.loadData(result, "text/html", null);
//myWebView.loadDataWithBaseURL("http://www.kibao.org",result, "text/html", "utf-8",null);
String lng = getResources().getString(R.string.lng);
myWebView.loadUrl(URL.concat(lng));
}
}
// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (stream != null) {
stream.close();
}
}
// StackOverflowXmlParser returns a List (called "entries") of Entry objects.
// Each Entry object represents a single post in the XML feed.
// This section processes the entries list to combine each entry with HTML markup.
// Each entry is displayed in the UI as a link that optionally includes
// a text summary.
return pagina;
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
Please help me to understand my mistake.
Thanks a lot,
Nino V
I found my mistake: it was a very stupid one! It was in my arrays.xml where I localized both names and values, so the code didn't recognize the value "ANY" which in my Italian phone was "Qualsiasi"!
Thank you for your attention.
Nino V
Related
I'm trying to use a AsyncTask to check if internet connection is available and then doing some stuff.
My problem is while the comprobation is being executed I canĀ“t interacting with the UI. The "progressbar" is on front and if I try to click on a button the UI doesn't respond
This is the call to AsyncTask
#Override
public void onStart(){
super.onStart();
AsyncHttpHandler check = new AsyncHttpHandler(**paramaters**);
check.execute("checkshared");
}
This is the code of AsyncTask
public class AsyncHttpHandler extends AsyncTask<String, Integer, String>{
public AsyncHttpHandler(Context c, Intent i, Bundle _data, String _language){
ctx = c;
intent = i;
data = _data;
language = _language;
startClock();
}
public void startClock(){
mDialog = new ProgressDialog(ctx,R.style.MyTheme);
mDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
mDialog.setCancelable(false);
mDialog.show();
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... peticion) {
String response = "null";
//call to check if internet connection is available
if(Utils.isInternetConn(ctx)){
try {
// do stuff
response = "...";
}
else response = "offline";
return response;
}
}
protected void onPostExecute(String response) {
if(mDialog != null) mDialog.dismiss();
if(!response.equals("offline")){
// do stuff
}
else Toast.makeText(ctx, ctx.getResources().getString(ctx.getResources().getIdentifier(language+"_toast_nointernet", "string", ctx.getPackageName())), Toast.LENGTH_LONG).show();
}
}
And this is the method to check if the internet connection is available:
public static Boolean isInternetConn(Context ctx){
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean conectado = false;
if((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL myurl = new URL("http://www.google.com");
URLConnection connection;
connection = myurl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
conectado = true;
httpConnection.disconnect();
}
else {
httpConnection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conectado;
}
What am I doing wrong?
The problem is not in your AsyncTask calling static method. That will also execute async. Problem is that you are showing progress dialog until your task finishes. And, of course, while your progress dialog is visible you will not be able to interact with the UI. If you want to interact with the UI, show your progress in another way, not with dialog.
You display a progressDialog on top of the screen. The progress dialog takes the UI interaction, so the buttons underneath don't respond. If you use a progress bar in your UI instead of a progress dialog, your buttons will work.
If you want to show the progress of your task to the user, use the method onProgressUpdate, as it has been implemented to run on the UI thread.
Now, each time you want to show the progress from doInBackground, call it by passing an argument. To be clear, AsyncTask (String, Integer, String) uses argument types:
First is the type of argument you pass when you call execute
Second is the type of the argument you pass to onProgressUpdate
Third is the type of argument you pass to onPostExecute
I'm not sure if I understood what is your problem, but it seems to me, that you cannot interact with UI because the ProgressDialog is not cancelable, and it's in front of everything else.
You will only have feedback when dialog is dismissed.
This question already has answers here:
Save webview content for offline browsing?
(2 answers)
Closed 8 years ago.
How to show web page even if internet is not connected? And if internet is connected than website should be loaded on webview
..
I am new for android and i needed an app. i checked over internet and created app.
my dashboard code is :
public class Dashboard extends Activity {
public String BASE_URL = "http://mywebsite.com/";
public String DASHBOARD_URL = BASE_URL;
private JavascriptInterface jsInterface;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
WebView engine = (WebView) findViewById(R.id.web_engine);
// Progress bar.
// With full screen app, window progress bar (FEATURE_PROGRESS) doesn't seem to show,
// so we use an explicitly created one.
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
engine.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
progressBar.setProgress(progress);
}
});
engine.setWebViewClient(new FixedWebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
jsInterface.enablePreferencesMenu = false;
jsInterface.modalIsVisible = false;
jsInterface.urlForSharing = null;
progressBar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
progressBar.setVisibility(View.GONE);
}
});
engine.getSettings().setJavaScriptEnabled(true);
jsInterface = new JavascriptInterface();
try {
ComponentName comp = new ComponentName(this, Dashboard.class);
PackageInfo pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
jsInterface.versionCode = pinfo.versionCode;
} catch(android.content.pm.PackageManager.NameNotFoundException e) {
}
engine.addJavascriptInterface(jsInterface, "Title");
engine.loadUrl(BASE_URL);
}
private WebView getEngine() {
return (WebView) findViewById(R.id.web_engine);
}
public void onBackPressed() {
WebView engine = getEngine();
String url = engine.getUrl();
if (jsInterface.modalIsVisible) {
engine.loadUrl("javascript: android.hideModal();");
} else if (url != null && (
url.equals(BASE_URL) ||
url.equals(DASHBOARD_URL) ||
!engine.canGoBack())) {
// exit
super.onBackPressed();
} else {
// go back a page, like normal browser
engine.goBack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem prefs = menu.findItem(R.id.preferences_menuitem);
if (prefs != null) {
prefs.setVisible(jsInterface.enablePreferencesMenu);
}
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.dashboard_menuitem:
getEngine().loadUrl(DASHBOARD_URL);
return true;
case R.id.refresh_menuitem:
getEngine().reload();
return true;
case R.id.preferences_menuitem:
getEngine().loadUrl("javascript: android.showPreferences()");
return true;
case R.id.contact_menuitem:
AboutBox.Show(Dashboard.this);
return true;
case R.id.share_url_menuitem:
final String url = (jsInterface.urlForSharing != null
? jsInterface.urlForSharing
: getEngine().getUrl());
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Android URL");
i.putExtra(Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(i, "Share"));
default:
return super.onOptionsItemSelected(item);
}
}
private class FixedWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(BASE_URL) || url.startsWith("javascript:")) {
// handle by the WebView
return false;
} else if (url.startsWith("mailto:")) {
MailTo mt = MailTo.parse(url);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
i.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
i.putExtra(Intent.EXTRA_CC, mt.getCc());
i.putExtra(Intent.EXTRA_TEXT, mt.getBody());
view.getContext().startActivity(i);
view.reload();
return true;
} else {
// Use external browser for anything not on this site
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(i);
return true;
}
}
}
// The methods of JavascriptInterface are called from javascript.
// The attributes are accessed from the Dashboard class.
// This is deliberately a dumb container class to stop possible
// security issues of javascript controlling Java app.
final class JavascriptInterface {
public boolean enablePreferencesMenu = false;
public boolean modalIsVisible = false;
public int versionCode = 0;
public String urlForSharing = null;
public void setEnablePreferencesMenu() {
enablePreferencesMenu = true;
}
public void setModalIsVisible(boolean visible) {
modalIsVisible = visible;
}
// This is useful for allowing the web site to be able to detect
// old app versions and prompt the user to upgrade.
public int getVersionCode() {
return versionCode;
}
public void setUrlForSharing(String url) {
urlForSharing = url;
}
}
}
Where should i edit to show no network connected message if device is not connected to internet???
First you need to check whether or not internet is connected to your device, you can check internet connection with below method
public static boolean checkNetworkConnection(Context _context){
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;
}
This method will return either true[If internet is connected] or false[if not connected]
Based on that true or false value you can decide whether to display html page or web page
Now Question is if you want to display webpage from your local folder than you can do it like this
You can load local html file as below
WebView lWebView = (WebView)findViewById(R.id.webView);
File lFile = new File(Environment.getExternalStorageDirectory() + "<FOLDER_PATH_TO_FILE>/<FILE_NAME>");
lWebView.loadUrl("file:///" + lFile.getAbsolutePath());
And if you want to display cahed html page than you need to do some R & D task for that.
Now if internet is connected than you can use below method to display web page on webview
wbb = (WebView) findViewById(R.id.webView_tobe_loaded);
WebSettings wbset=wbb.getSettings();
wbset.setJavaScriptEnabled(true);
wbb.setWebViewClient(new MyWebViewClient());
String url="http://www.google.com";
System.out.println(getdeviceid());
wbb.getSettings().setJavaScriptEnabled(true);
wbb.loadUrl(url);
I hope you understood all the explanation
You can check for internet connection using this:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
more info here: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
And to show HTML without load it from the internet:
webview.loadData("<b>Connection not availeable</b>", "text/html", null);
more info: http://developer.android.com/reference/android/webkit/WebView.html#loadData(java.lang.String,java.lang.String, java.lang.String)
My app sends data to the server. It generally works fine until the user is in a bad signal area. If the user is in a good signal area the the following code works fine and the data is sent.
String[] params = new String[]{compID, tagId, tagClientId, carerID,
formattedTagScanTime, formattedNowTime, statusForWbService, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd = new AsyncPostData();
apd.execute(params);
.
private class AsyncPostData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String dateTimeScanned;
#Override
protected void onPreExecute()
{
// progressDialog= ProgressDialog.show(NfcscannerActivity.this,
// "Connecting to Server"," Posting data...", true);
int buildVersionSdk = Build.VERSION.SDK_INT;
int buildVersionCodes = Build.VERSION_CODES.GINGERBREAD;
Log.e(TAG, "buildVersionSdk = " + buildVersionSdk
+ "buildVersionCodes = " + buildVersionCodes);
int themeVersion;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
themeVersion = 2;
}else{
themeVersion = 1;
}
progressDialog = new ProgressDialog(NfcscannerActivity.this, themeVersion);
progressDialog.setTitle("Connecting to Server");
progressDialog.setMessage(" Sending data to server...");
progressDialog.setIndeterminate(true);
try{
progressDialog.show();
}catch(Exception e){
//ignore
}
};
#Override
protected String doInBackground(String... params) {
Log.e(TAG, "carerid in doinbackground = " + params[3] + " dateTimeScanned in AsyncPost for the duplecate TX = " + params[4]);
dateTimeScanned = params[4];
return nfcscannerapplication.loginWebservice.postData(params[0], params[1], params[2], params[3], params[4],
params[5], params[6], params[7] + getVersionName(), params[8], params[9]);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try{
progressDialog.dismiss();
}catch(Exception e){
//ignore
}
if( result != null && result.trim().equalsIgnoreCase("OK") ){
Log.e(TAG, "about to update DB with servertime");
DateTime sentToServerAt = new DateTime();
nfcscannerapplication.loginValidate.updateTransactionWithServerTime(sentToServerAt,null);
nfcscannerapplication.loginValidate.insertIntoDuplicateTransactions(dateTimeScanned);
tagId = null;
tagType = null;
tagClientId = null;
//called to refresh the unsent transactions textview
onResume();
}else if(result != null && result.trim().equalsIgnoreCase("Error: TX duplicated")){
Log.e(TAG, "response from server is Duplicate Transaction ");
//NB. the following time may not correspond exactly with the time on the server
//because this TX has already been processed but the 'OK' never reached the phone,
//so we are just going to update the phone's DB with the DupTX time so the phone doesn't keep
//sending it.
DateTime sentToServerTimeWhenDupTX = new DateTime();
nfcscannerapplication.loginValidate.updateTransactionWithServerTime(sentToServerTimeWhenDupTX,null);
tagId = null;
tagType = null;
tagClientId = null;
}else{
Toast.makeText(NfcscannerActivity.this,
"No phone signal or server problem",
Toast.LENGTH_LONG).show();
}
}
}//end of AsyncPostData
.
The app in bad signal areas tends to show the progress bar for a few minutes before showing a black screen for a while rendering the app unusable.
I thought a way around this would be to do the following.
String[] params = new String[]{compID, tagId, tagClientId, carerID,
formattedTagScanTime, formattedNowTime, statusForWbService, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd = new AsyncPostData();
try {
apd.execute(params).get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This will cause the AsyncTask to cancel after 10 seconds, but as it is executing there is a black screen until the data is sent followed by the progressbar for a few millisecs.
Is there a way to show the progressbar whilst executing an AsyncTask.get()?
thanks in advance. matt.
Also are there any ideas why the black screen comes when the user is in bad signal area and therefor no response from the server. This senario seems to cause the app alot of problems where it's behavior is unusual afterwards like sending extra transactions at a later date.
[edit1]
public class SignalService extends Service{
NfcScannerApplication nfcScannerApplication;
TelephonyManager SignalManager;
PhoneStateListener signalListener;
private static final int LISTEN_NONE = 0;
private static final String TAG = SignalService.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
// TODO Auto-generated method stub
Log.e(TAG, "SignalService created");
nfcScannerApplication = (NfcScannerApplication) getApplication();
signalListener = new PhoneStateListener() {
public void onSignalStrengthChanged(int asu) {
//Log.e("onSignalStrengthChanged: " , "Signal strength = "+ asu);
nfcScannerApplication.setSignalStrength(asu);
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
Log.e(TAG, "SignalService destroyed");
SignalManager.listen(signalListener, LISTEN_NONE);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// TODO Auto-generated method stub
Log.e(TAG, "SignalService in onStart");
SignalManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
SignalManager.listen(signalListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You do not need a timer at all to do what you're attempting (for some reason I thought you were trying to loop the AsyncTask based on your comments above which resulted in mine.). If I understand correctly you're issue is with the loss of service. You have an AsyncTask that you start which may or may not finish depending on certain conditions. Your approach was to use get and cancle the task after a fixed time in the event that it did not finish executing before then - the assumption being if the task didn't finish within the 10 second cut off, service was lost.
A better way to approach this problem is to use a boolean flag that indcates whether network connectivity is available and then stop the task from executing if service is lost. Here is an example I took from this post (I apologize for the formatting I'm on a crappy computer with - of all things - IE8 - so I can't see what the code looks like).
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected void onCancelled() {
running = false;
}
#Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
This example uses a progress dialog that allows the user to cancle the task by pressing a button. You're not going to do that but rather you're going to check for network connectivty and set the running boolean based on whether your task is connected to the internet. If connection is lost - running will bet set to false which will trip the while loop and stop the task.
As for the work after the task complete. You should NEVER use get. Either (1) put everything that needs to be done after the doInBackgroundCompletes in onPostExecute (assuming its not too much) or (2) if you need to get the data back to the starting activity use an interface. You can add an interface by either adding as an argument to your tasks constructor or using a seperate method that sets the interface up. For example
public void setInterface(OnTaskComplete listener){
this.listener = listener;
}
Where OnTaskComplete listener is declared as an instance variable in your AsyncTask. Note the approach I am describing requires using a seperate AsyncTask class. Your's is private right now which means you need to change your project a little.
UPDATE
To check connectivity I would use something like this.
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}else {
netInfo = cm.getNetworkInfo(1);
if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
You can check to see if there is an actual network connection over which your app can connect to ther server. This method doesn't have to be public and can be part of you're AsyncTask class. Personally, I use something similar to this in a network manager class that I use to check various network statistics (one of which is can I connect to the internet).
You would check connectivity before you started executing the loop in your doInBackground method and then you could periodicly update throughout the course of that method. If netowkr is available the task will continue. If not it will stop.
Calling the AsyncTask built in cancle method is not sufficient becuase it only prevent onPostExecute from running. It does not actually stop the code from execting.
This is my first question in SO. I am new (and excited) in Android programming and here is my PROBLEM: I am building a project using my android phone and a microcontroller. The microcontroller has a distance sensor and transmits its value. I have managed to get connected to the microcontroller and send correct signals, but I can't get the distance mesurment, or anything else. The application doesn't crash or anything it just won't get the data from the microcontroller (my computer gets the data from microcontroler (data is a string)). My code from the android app is this:
public class Accelerometer extends Activity {
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final int RECIEVE_MESSAGE = 3;
// Program variables
private byte microcOut;
private boolean ledStat;
private boolean connectStat = false;
private Button btnled;
private Button connect_button;
private TextView yAccel, xAccel, incoming;
protected static final int MOVE_TIME = 80;
private long lastWrite = 0;
OnClickListener myClickListener;
ProgressDialog myProgressDialog;
private Toast failToast;
private Handler mHandler,h;
private StringBuilder sb = new StringBuilder();
// Sensor object used to handle accelerometer
private SensorManager mySensorManager;
private List<Sensor> sensors;
private Sensor accSensor;
// Bluetooth Stuff
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private InputStream inStream = null;
private ConnectThread mConnectThread = null;
private ConnectedThread mConnectedThread;
private String deviceAddress = null;
// Well known SPP UUID (will *probably* map to RFCOMM channel 1 (default) if not in use);
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Sound Clip to make app prettier
MediaPlayer myclip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_accelerometer);
myclip = MediaPlayer.create(this, R.raw.cartcar);
myclip.start();
// Finds buttons in .xml layout file
btnled = (Button) findViewById(R.id.led_button1);
connect_button = (Button) findViewById(R.id.connect_button1);
yAccel = (TextView) findViewById(R.id.accText1);
xAccel = (TextView) findViewById(R.id.accText2);
incoming = (TextView) findViewById(R.id.incoming);
// Set Sensor
mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = mySensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors.size() > 0) accSensor = sensors.get(0);
myProgressDialog = new ProgressDialog(this);
failToast = Toast.makeText(this, R.string.failedToConnect, Toast.LENGTH_SHORT);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (myProgressDialog.isShowing()) {
myProgressDialog.dismiss();
}
// Check if bluetooth connection was made to selected device
if (msg.what == 1) {
// Set button to display current status
connectStat = true;
connect_button.setText(R.string.connected);
// Reset the BluCar
microcOut = 0;
ledStat = false;
write(microcOut);
}else {
// Connection failed
failToast.show();
}
}
};
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
incoming.setText("Data from Arduino: " + sbprint); // update TextView
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
// Check whether bluetooth adapter exists
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
finish();
return;
}
// If BT is not on, request that it be enabled.
if (!btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
/**********************************************************************
* Buttons for controlling BluCar
*/
connect_button.setOnClickListener(new View.OnClickListener() {
// Connect to Bluetooth Module
#Override
public void onClick(View v) {
if (connectStat) {
// Attempt to disconnect from the device
disconnect();
}else{
// Attempt to connect to the device
connect();
}
}
});
// Toggle Headlights
btnled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ledStat) {
microcOut = (byte) (microcOut & 124);
btnled.setText(R.string.ledbuttonON);
ledStat = false;
}else{
microcOut = (byte) (microcOut | 128);
btnled.setText(R.string.ledbuttonOFF);
ledStat = true;
}
write(microcOut);
}
});
}
/** Thread used to connect to a specified Bluetooth Device */
public class ConnectThread extends Thread {
private String address;
private boolean connectionStatus;
ConnectThread(String MACaddress) {
address = MACaddress;
connectionStatus = true;
}
public void run() {
// When this returns, it will 'know' about the server,
// via it's MAC address.
try {
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// We need two things before we can successfully connect
// (authentication issues aside): a MAC address, which we
// already have, and an RFCOMM channel.
// Because RFCOMM channels (aka ports) are limited in
// number, Android doesn't allow you to use them directly;
// instead you request a RFCOMM mapping based on a service
// ID. In our case, we will use the well-known SPP Service
// ID. This ID is in UUID (GUID to you Microsofties)
// format. Given the UUID, Android will handle the
// mapping for you. Generally, this will return RFCOMM 1,
// but not always; it depends what other BlueTooth services
// are in use on your Android device.
try {
btSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
connectionStatus = false;
}
}catch (IllegalArgumentException e) {
connectionStatus = false;
}
// Discovery may be going on, e.g., if you're running a
// 'scan for devices' search from your handset's Bluetooth
// settings, so we call cancelDiscovery(). It doesn't hurt
// to call it, but it might hurt not to... discovery is a
// heavyweight process; you don't want it in progress when
// a connection attempt is made.
btAdapter.cancelDiscovery();
// Blocking connect, for a simple client nothing else can
// happen until a successful connection is made, so we
// don't care if it blocks.
try {
btSocket.connect();
} catch (IOException e1) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e2) {
connectionStatus = false;
}
// Send final result
if (connectionStatus) {
mHandler.sendEmptyMessage(1);
}else {
mHandler.sendEmptyMessage(0);
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Show please wait dialog
myProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.pleaseWait), getResources().getString(R.string.makingConnectionString), true);
// Get the device MAC address
deviceAddress = data.getExtras().getString(DeviceList.EXTRA_DEVICE_ADDRESS);
// Connect to device with specified MAC address
mConnectThread = new ConnectThread(deviceAddress);
mConnectThread.start();
}else {
// Failure retrieving MAC address
Toast.makeText(this, R.string.macFailed, Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
public void write(byte data) {
if (outStream != null) {
try {
outStream.write(data);
} catch (IOException e) {
}
}
}
public void emptyOutStream() {
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
}
}
}
public void connect() {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceList.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
public void disconnect() {
if (outStream != null) {
try {
outStream.close();
connectStat = false;
connect_button.setText(R.string.disconnected);
} catch (IOException e) {
}
}
}
private final SensorEventListener mSensorListener = new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
#Override
public void onSensorChanged(SensorEvent event) {
// Checks whether to send steering command or not
long date = System.currentTimeMillis();
if (date - lastWrite > MOVE_TIME) {
yAccel.setText(" " + event.values[1]);
xAccel.setText(" " + event.values[0]);
if (event.values[1] > 2.5) {
// Turn right
microcOut = (byte) (microcOut & 248);
microcOut = (byte) (microcOut | 4);
}else if (event.values[1] < -2.5) {
// Turn left
microcOut = (byte) (microcOut & 244);
microcOut = (byte) (microcOut | 8);
}else {
// Center the steering servo
microcOut = (byte) (microcOut & 240);
}
write(microcOut);
lastWrite = date;
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_accelerometer, menu);
return true;
}
public void onResume() {
super.onResume();
mySensorManager.registerListener(mSensorListener, accSensor, SensorManager.SENSOR_DELAY_GAME);
}
#Override
public void onDestroy() {
emptyOutStream();
disconnect();
if (mSensorListener != null) {
mySensorManager.unregisterListener(mSensorListener);
}
super.onDestroy();
myclip.release();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
}
}
}
}
I have read everything over the subject (BluetoothChat, projects of people on the internet ...) and I am very tired. Any help is much appreciated.
--EDIT--
I have managed to get the inputstream into my texteview. My problem now is that my application when it is trying to connect to my device (microcontroller or my pc) gets stuck in the progressdialog (it is connected to the device but the progressdialog will not go away)and waits for something to come in. After a while (like 5-6 secs) even if something comes in it remains stuck and I have to force it to close. I think the problem is in the way the handler handles the thread. In the debugger there is no problem all threads run ok.
The changes in my code are:
In my ConnectThread:
`/** Thread used to connect to a specified Bluetooth Device */
public class ConnectThread extends Thread {
private String address;
private boolean connectionStatus;
ConnectThread(String MACaddress) {
address = MACaddress;
connectionStatus = true;
}
public void run() {
// When this returns, it will 'know' about the server,
// via it's MAC address.
try {
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// We need two things before we can successfully connect
// (authentication issues aside): a MAC address, which we
// already have, and an RFCOMM channel.
// Because RFCOMM channels (aka ports) are limited in
// number, Android doesn't allow you to use them directly;
// instead you request a RFCOMM mapping based on a service
// ID. In our case, we will use the well-known SPP Service
// ID. This ID is in UUID (GUID to you Microsofties)
// format. Given the UUID, Android will handle the
// mapping for you. Generally, this will return RFCOMM 1,
// but not always; it depends what other BlueTooth services
// are in use on your Android device.
try {
btSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
connectionStatus = false;
}
}catch (IllegalArgumentException e) {
connectionStatus = false;
}
// Discovery may be going on, e.g., if you're running a
// 'scan for devices' search from your handset's Bluetooth
// settings, so we call cancelDiscovery(). It doesn't hurt
// to call it, but it might hurt not to... discovery is a
// heavyweight process; you don't want it in progress when
// a connection attempt is made.
btAdapter.cancelDiscovery();
// Blocking connect, for a simple client nothing else can
// happen until a successful connection is made, so we
// don't care if it blocks.
try {
btSocket.connect();
} catch (IOException e1) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e2) {
connectionStatus = false;
}
try{
inStream = btSocket.getInputStream();
}catch (IOException e2){
connectionStatus = false;
}
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (connectionStatus) {
try {
byte[] b = new byte[64]; // buffer store for the stream
// Read from the InputStream
bytes = inStream.read(b); // Get number of bytes and message in "buffer"
mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, b).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
// Send final result
if (connectionStatus) {
mHandler.obtainMessage(1);
}else {
mHandler.sendEmptyMessage(0);
}
}
}
`
And in my mHandler in my onCreate method:
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (myProgressDialog.isShowing()) {
myProgressDialog.dismiss();
}
// Check if bluetooth connection was made to selected device
if (msg.what == 1) {
// Set button to display current status
connectStat = true;
connect_button.setText(R.string.connected);
// Reset the BluCar
microcOut = 0;
ledStat = false;
write(microcOut);
}else if (msg.what == 2){
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("."); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
incoming.setText(sbprint); // update TextView
connectStat = true;
connect_button.setText(R.string.connected);
}else{
incoming.setText("Problem!");
}
}else {
// Connection failed
failToast.show();
}
}
};
Another thing I need is how to empty the buffer when it is full.
PS: Thanks EVERYONE for his/her help I am really grateful.
As an alternative to using the handler, just get the information in the run of the thread..
I have done it this way and it works for me.
public void run() {
byte[] buffer = new byte[128]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
bytes = mmInStream.read(buffer);
byte[] readBuf = (byte[]) buffer;
String strIncom = new String(readBuf, 0, bytes); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) {
// add the current string to eol to a local string
String sbprint = sb.substring(0, endOfLineIndex);
// get the start and end indexes of the heading
int startHeading = sb.indexOf("HE");
int endHeading = sb.indexOf("/HE");
// set the heading
Henry.this.setCurrentHeading(sb.substring((startHeading + 2), endHeading));
// get the start and end indexes of the front range
int startFrontRange = sb.indexOf("FR");
int endFrontRange = sb.indexOf("/FR");
// get the front range
Henry.this.currentFrontRange = sb.substring((startFrontRange + 2), endFrontRange);
... ( grab all the information you need here ) ...
// debugging output what we have
// System.out.println("recv: " + sbprint);
// clean out the sb to ready next run
sb.delete(0, sb.length());
}
I save all the information retrieved from the serial connection in my Application (Henry), then any Activity that wants to use the info gets it from the application. If the view needs to have a updated perspective on the information, I add a timer to the view to kick of a refresh method as often as I like. This has the added advantage of being able to use the information from anywhere in your android application.
I send about 10 data points from the arduino to the device and about 3 data points from the device to the arduino this way. I added my own markup around the datapoints to identify them.
Hope this helps!
I have an application that uses Internet connection but when there is no internet connection available the application stop responding. Can anyone help on how i can resolve this problem. What I have thought that i can display an error when there no internet connection available but I dont know the way to do it.
Required permission is :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Check Internet connection for each request
public boolean isOnline() {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
Use above method as
if(isOnline()) {
//Write code of request
} else {
showDialog("Internet connection error", "Connection is not available.")
}
Show dialog method
private void showDialog(String title, String text) {
// Access denied. Show dialogue to user
AlertDialog.Builder alertbox = new AlertDialog.Builder(YOUR_ACTIVITY.this);
alertbox.setTitle(title);
alertbox.setIcon(android.R.drawable.ic_dialog_info);
alertbox.setMessage(text);
alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//finish(); //DO nothing
}
});
alertbox.show();
}
Edited :
Replace YOUR_ACTIVITY.this with activity name in which your are using this code.
You can show an AlertDialog to show the user that there is no internet connection.And if your application can't go on without connection,after clickin cancel button in AlertDialog, you can finish your activity and close the application.
Check out my HTTPclass.java class, how I did that, I have a method connect(url) that takes a String of url and connects it, if connection is received it responds and gives the responseCode = 200 or HTTP.OK, and if the connection is not connected I handle a catch block and set the responseCode = -1 which means its not connected.
So, you can do something like that only. When responsecode is -1 you can show the Message that "Internet Not Connected".
public class HTTPClass
{
private static int responseCode = -1;
private static HttpURLConnection httpconn = null;
private static URLConnection conn = null;
private static URL urlobj;
public static int connect(String url) throws IOException
{
try
{
urlobj = new URL(url);
conn = urlobj.openConnection();
httpconn= (HttpURLConnection)conn;
httpconn.setConnectTimeout(5000);
httpconn.setDoInput(true);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
responseCode = httpconn.getResponseCode();
}
catch(Exception e)
{
responseCode = -1;
e.printStackTrace();
}
return responseCode;
}
}