Broadcast Receiver never called for WifiManager? (Android Wear) - android

I need to create an app to scan and gather the list of access points available, including the signal strength. For some reason every time I initiate the WifiManager.startScan() method, it returns true, but my Broadcast Receiver is never called.
Here is the code for my class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Manages radio (wifi) information
*/
public class NetworkManager {
private final Handler handler = new Handler();
private WifiReceiver receiverWifi;
private TextView mTextView;
// true if scan is done
private boolean mDone = true;
private WifiManager mManager;
List<ScanResult> results;
// Data in form SSID, RSSI
ArrayList<HashMap<String, String>> oldData = new ArrayList<>();
ArrayList<HashMap<String, String>> data = new ArrayList<>();
public NetworkManager(Context c, TextView mTextView) {
this.mTextView = mTextView;
mManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if (!mManager.isWifiEnabled())
mManager.setWifiEnabled(true);
receiverWifi = new WifiReceiver();
c.registerReceiver(receiverWifi,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
if (mManager.isWifiEnabled() == false)
mManager.setWifiEnabled(true);
scanAndSet();
Log.d("TAG", "Constructor after scan and set");
WifiInfo wifiInfo = mManager.getConnectionInfo();
Log.d("TAG", wifiInfo.toString());
}
/**
* Sets the SSID and RSSI from the scanned results into main data bin.
*/
// private void setNetworkData() {
// String result = "";
// oldData = data;
// data.clear();
// for(ScanResult r : results) {
// String ssid = r.SSID;
// String rssi = String.valueOf(r.level);
// HashMap<String, String> x = new HashMap<>();
// x.put(ssid, rssi);
// result += "ID: " + ssid + " - RSSI" + rssi + "/n";
// Log.d("TAG", "R: " + result);
// }
// mDone = true;
// }
public void scanAndSet() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("TAG", "Start: " + mManager.startScan());
}
});
}
public boolean isDone() {
return mDone;
}
class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "On receive broadcast receiver");
ArrayList<String> connections=new ArrayList<String>();
ArrayList<Float> Signal_Strenth= new ArrayList<Float>();
List<ScanResult> wifiList = mManager.getScanResults();
for(int i = 0; i < wifiList.size(); i++) {
connections.add(wifiList.get(i).SSID);
}
}
}
}
the scanAndSet() method is suppose to initiate the scan. The startScan() method returns true. The receiver is only called when I go to the settings and the device searches for wifi networks, I can't seem to do it programatically.
Another peculiar thing is when I want to get information for the connected access point using WifiManager.getConnectionInfo().toString(), this is what it gives.
D/TAG: SSID: <unknown ssid>, BSSID: <none>, Supplicant state: COMPLETED, RSSI: -127, Link speed: -1Mbps, Frequency: -1MHz, Net ID: -1, Metered hint: false, score: 0
I'm completely lost, is this common with all Wear devices or is the wifi api disabled?

Related

Android Studio: Bluetooth Low Energy BLE Advertisements

on line 370 i need a way to look for a string of 'f's' in the advertisement data from a TI CC2650. I found this template online but I'm looking for specific advertising data. Please let me know what string array I need to look at to find this.
package net.jmodwyer.beacon.beaconPoC;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import net.jmodwyer.ibeacon.ibeaconPoC.R;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.utils.UrlBeaconUrlCompressor;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* Adapted from original code written by D Young of Radius Networks.
* #author dyoung, jodwyer
*
*/
public class ScanActivity extends Activity implements BeaconConsumer,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// Constant Declaration
private static final String PREFERENCE_SCANINTERVAL = "scanInterval";
private static final String PREFERENCE_TIMESTAMP = "timestamp";
private static final String PREFERENCE_POWER = "power";
private static final String PREFERENCE_PROXIMITY = "proximity";
private static final String PREFERENCE_RSSI = "rssi";
private static final String PREFERENCE_MAJORMINOR = "majorMinor";
private static final String PREFERENCE_UUID = "uuid";
private static final String PREFERENCE_INDEX = "index";
private static final String PREFERENCE_LOCATION = "location";
private static final String PREFERENCE_REALTIME = "realTimeLog";
private static final String MODE_SCANNING = "Stop Scanning";
private static final String MODE_STOPPED = "Start Scanning";
protected static final String TAG = "ScanActivity";
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int
CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private FileHelper fileHelper;
private BeaconManager beaconManager;
private Region region;
private int eventNum = 1;
// This StringBuffer will hold the scan data for any given scan.
private StringBuffer logString;
// Preferences - will actually have a boolean value when loaded.
private Boolean index;
private Boolean location;
private Boolean uuid;
private Boolean majorMinor;
private Boolean rssi;
private Boolean proximity;
private Boolean power;
private Boolean timestamp;
private String scanInterval;
// Added following a feature request from D.Schmid.
private Boolean realTimeLog;
// LocationClient for Google Play Location Services
LocationClient locationClient;
private ScrollView scroller;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
verifyBluetooth();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
BeaconScannerApp app = (BeaconScannerApp)this.getApplication();
beaconManager = app.getBeaconManager();
//beaconManager.setForegroundScanPeriod(10);
region = app.getRegion();
beaconManager.bind(this);
locationClient = new LocationClient(this, this, this);
fileHelper = app.getFileHelper();
scroller = (ScrollView)ScanActivity.this.findViewById(R.id.scanScrollView);
editText = (EditText)ScanActivity.this.findViewById(R.id.scanText);
// Initialise scan button.
getScanButton().setText(MODE_STOPPED);
}
#Override
public void onResume() {
super.onResume();
beaconManager.bind(this);
}
#Override
public void onPause() {
super.onPause();
// Uncommenting the following leak prevents a ServiceConnection leak when using the back
// arrow in the Action Bar to come out of the file list screen. Unfortunately it also kills
// background scanning, and as I have no workaround right now I'm settling for the lesser of
// two evils.
// beaconManager.unbind(this);
}
public String getCurrentLocation() {
/** Default "error" value is set for location, will be overwritten with the correct lat and
* long values if we're ble to connect to location services and get a reading.
*/
String location = "Unavailable";
if (locationClient.isConnected()) {
Location currentLocation = locationClient.getLastLocation();
if (currentLocation != null) {
location = Double.toString(currentLocation.getLatitude()) + "," +
Double.toString(currentLocation.getLongitude());
}
}
return location;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBeaconServiceConnect() {}
/**
*
* #param view
*/
public void onScanButtonClicked(View view) {
toggleScanState();
}
// Handle the user selecting "Settings" from the action bar.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Settings:
// Show settings
Intent api = new Intent(this, AppPreferenceActivity.class);
startActivityForResult(api, 0);
return true;
case R.id.action_listfiles:
// Launch list files activity
Intent fhi = new Intent(this, FileHandlerActivity.class);
startActivity(fhi);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Start and stop scanning, and toggle button label appropriately.
*/
private void toggleScanState() {
Button scanButton = getScanButton();
String currentState = scanButton.getText().toString();
if (currentState.equals(MODE_SCANNING)) {
stopScanning(scanButton);
} else {
startScanning(scanButton);
}
}
/**
* start looking for beacons.
*/
private void startScanning(Button scanButton) {
// Set UI elements to the correct state.
scanButton.setText(MODE_SCANNING);
((EditText)findViewById(R.id.scanText)).setText("");
// Reset event counter
eventNum = 1;
// Get current values for logging preferences
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
HashMap <String, Object> prefs = new HashMap<String, Object>();
prefs.putAll(sharedPrefs.getAll());
index = (Boolean)prefs.get(PREFERENCE_INDEX);
location = (Boolean)prefs.get(PREFERENCE_LOCATION);
uuid = (Boolean)prefs.get(PREFERENCE_UUID);
majorMinor = (Boolean)prefs.get(PREFERENCE_MAJORMINOR);
rssi = (Boolean)prefs.get(PREFERENCE_RSSI);
proximity = (Boolean)prefs.get(PREFERENCE_PROXIMITY);
power = (Boolean)prefs.get(PREFERENCE_POWER);
timestamp = (Boolean)prefs.get(PREFERENCE_TIMESTAMP);
scanInterval = (String)prefs.get(PREFERENCE_SCANINTERVAL);
realTimeLog = (Boolean)prefs.get(PREFERENCE_REALTIME);
// Get current background scan interval (if specified)
if (prefs.get(PREFERENCE_SCANINTERVAL) != null) {
beaconManager.setBackgroundBetweenScanPeriod(Long.parseLong(scanInterval));
}
logToDisplay("Scanning...");
// Initialise scan log
logString = new StringBuffer();
//Start scanning again.
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
Iterator <Beacon> beaconIterator = beacons.iterator();
while (beaconIterator.hasNext()) {
Beacon beacon = beaconIterator.next();
// Debug - logging a beacon - checking background logging is working.
System.out.println("Logging another beacon.");
logBeaconData(beacon);
}
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
}
/**
* Stop looking for beacons.
*/
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0) {
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
/**
*
* #return reference to the start/stop scanning button
*/
private Button getScanButton() {
return (Button)findViewById(R.id.scanButton);
}
/**
*
* #param beacon The detected beacon
*/
private void logBeaconData(Beacon beacon) {
StringBuilder scanString = new StringBuilder();
if (index) {
scanString.append(eventNum++);
}
if (beacon.getServiceUuid() == 0xfeaa) {
if (beacon.getBeaconTypeCode() == 0x00) {
scanString.append(" Eddystone-UID -> ");
scanString.append(" Namespace : ").append(beacon.getId1());
scanString.append(" Identifier : ").append(beacon.getId2());
logEddystoneTelemetry(scanString, beacon);
} else if (beacon.getBeaconTypeCode() == 0x10) {
String url = UrlBeaconUrlCompressor.uncompress(beacon.getId1().toByteArray());
scanString.append(" Eddystone-URL -> " + url);
} else if (beacon.getBeaconTypeCode() == 0x20) {
scanString.append(" Eddystone-TLM -> ");
logEddystoneTelemetry(scanString, beacon);
}
} else {
// Just an old fashioned iBeacon or AltBeacon...
logGenericBeacon(scanString, beacon);
}
logToDisplay(scanString.toString());
scanString.append("\n");
// Code added following a feature request by D.Schmid - writes a single entry to a file
// every time a beacon is detected, the file will only ever have one entry as it will be
// recreated on each call to this method.
// Get current background scan interval (if specified)
if (realTimeLog) {
// We're in realtime logging mode, create a new log file containing only this entry.
fileHelper.createFile(scanString.toString(), "realtimelog.txt");
}
logString.append(scanString.toString());
}
/**
* Logs iBeacon & AltBeacon data.
*/
private void logGenericBeacon(StringBuilder scanString, Beacon beacon) {
// Comment stuff out for whatever reason
/*
if (location) {
scanString.append(" Location: ").append(getCurrentLocation()).append(" ");
}
`
*/
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
if (beacon.getId1().equals("ffffffff-ffff-ffff-ffff-ffffffffffff ")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT =( ");
}
/*
if ((beacon.getId1()).equals ("f")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT!!!!!!!!!!! ");
}
*/
}
// Making if statements to test for advertising data
/*
if (majorMinor) {
scanString.append(" Maj. Mnr.: ");
if (beacon.getId2() != null) {
scanString.append(beacon.getId2());
}
scanString.append("-");
if (beacon.getId3() != null) {
scanString.append(beacon.getId3());
}
}
if (rssi) {
scanString.append(" RSSI: ").append(beacon.getRssi());
}
if (proximity) {
scanString.append(" Proximity: ").append(BeaconHelper.getProximityString(beacon.getDistance()));
}
if (power) {
scanString.append(" Power: ").append(beacon.getTxPower());
}
if (timestamp) {
scanString.append(" Timestamp: ").append(BeaconHelper.getCurrentTimeStamp());
} */
}
private void logEddystoneTelemetry(StringBuilder scanString, Beacon beacon) {
// Do we have telemetry data?
if (beacon.getExtraDataFields().size() > 0) {
long telemetryVersion = beacon.getExtraDataFields().get(0);
long batteryMilliVolts = beacon.getExtraDataFields().get(1);
long pduCount = beacon.getExtraDataFields().get(3);
long uptime = beacon.getExtraDataFields().get(4);
scanString.append(" Telemetry version : " + telemetryVersion);
scanString.append(" Uptime (sec) : " + uptime);
scanString.append(" Battery level (mv) " + batteryMilliVolts);
scanString.append(" Tx count: " + pduCount);
}
}
/**
*
* #param line
*/
private void logToDisplay(final String line) {
runOnUiThread(new Runnable() {
public void run() {
editText.append(line + "\n");
// Temp code - don't really want to do this for every line logged, will look for a
// workaround.
Linkify.addLinks(editText, Linkify.WEB_URLS);
scroller.fullScroll(View.FOCUS_DOWN);
}
});
}
private void verifyBluetooth() {
try {
if (!BeaconManager.getInstanceForApplication(this).checkAvailability()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth not enabled");
builder.setMessage("Please enable bluetooth in settings and restart this application.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
catch (RuntimeException e) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth LE not available");
builder.setMessage("Sorry, this device does not support Bluetooth LE.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
/* Location services code follows */
#Override
protected void onStart() {
super.onStart();
// Connect the client.
locationClient.connect();
}
#Override
protected void onStop() {
// Disconnect the client.
locationClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle dataBundle) {
// Uncomment the following line to display the connection status.
// Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Toast.makeText(getBaseContext(),
"Location services not available, cannot track device location.",
Toast.LENGTH_SHORT).show();
}
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* TODO - Try the request again
*/
break;
}
}
}
}
Need to cast to string first .toString
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
// Making if statements to look for all f's in advertising data
if (beacon.getId1().toString().equals(Str1)){
scanString.append("\nAlarm ACTIVATED\n");
}else{
scanString.append("\n Alarm NOT active\n");
}
}

can rollback or downgrade the Android os to the previous one

thank you for reading my problem, and hopefully I will get help from you guys.
I have LG watch urbane , and the OS is updated to 6.0.1
unfortunately after the update, I have many problems in the applications on my wear. is there any solution that I can rollback or downgrade the Android os to the previous one?
or could anyone help me with this code please?
I have an application that collects the motion data from Accelerometer and gyroscope wear sensors for five min.
I set the timestamp to 20hz per second (so I should get 20 samples per second from each sensor, thus 6000 samples(records) every 5 min). However, after 5 mins, I have got 30,000 samples( records) from Accelerometer sensor, and 6000 from gyroscope sensor, which is exactly what I want , but the problem with Accelerometer sensor. this problem didn't exist with the old OS of the wear. it appeared after the update. before the update of the Wear OS, I was getting the same number of samples from both sensors every five min (6000 records).
bellow is the code for the App
package edu.fordham.cis.wisdm.actipebble;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.*;
import java.lang.*;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.common.collect.Lists;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Handles the collection of data and the transmission of the data back to the phone in batches.
* #author Andrew H. Johnston ajohnston9#fordham.edu
* #version 1.0STABLE
*/
public class WearTrainingActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mGyroscope;
private TextView mPrompt;
private TextView mProgress;
private GoogleApiClient googleApiClient;
private ArrayList<AccelerationRecord> mAccelerationRecords = new ArrayList<AccelerationRecord>();
private ArrayList<GyroscopeRecord> mGyroscopeRecords = new ArrayList<GyroscopeRecord>();
/**
* Tells the Sensor if it should save the records it
*/
private boolean shouldCollect = false;
/**
* Debugging tag
*/
private static final String TAG = "WearTrainingActivity";
/**
* One of the strategies to keep the watch screen on
*/
private PowerManager.WakeLock wakeLock;
/**
* Constant used to add clarity to formulae below
*/
private static final short MILLIS_IN_A_SECOND = 1000;
/**
* Change the second (i.e. 2nd) multiplicand to change the number of seconds of data collected
*/
private int delay = MILLIS_IN_A_SECOND * 300;
/**
* Expressed in a formula so that value makes more sense
*/
private int maxNumRecords = (delay / MILLIS_IN_A_SECOND) * 20;
/**
* Keeps track of the number of records obtained. This is more accurate than a time-based
* approach.
*/
private int recordCount = 0;
/**
* Sample rate, expressed as number of microseconds between samplings
*/
private static final int SAMPLE_RATE = 50000;
/**
* Maximum number of records we can send to the phone in one transmission.
*/
private static final int MAX_RECORDS_SENT_AT_ONCE = 3500;
/**
* Flag that signals the end of data transmission to the phone
*/
private static final String DATA_COLLECTION_DONE = "/thats-all-folks";
private static boolean first = true;
private static long first_time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_training);
//Easy way to keep watch from sleeping on me
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mProgress = (TextView) findViewById(R.id.txtProgress);
mPrompt = (TextView) findViewById(R.id.txtPrompt);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mProgress = (TextView) findViewById(R.id.txtProgress);
mPrompt = (TextView) findViewById(R.id.txtPrompt);
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
//Collect at 20Hz (Once every 50,000 microseconds)
mSensorManager.registerListener(this, mAccelerometer, SAMPLE_RATE);
mSensorManager.registerListener(this, mGyroscope, SAMPLE_RATE);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "Connected to phone.");
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Connection to phone suspended. Code: " + i);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Fuck! Connection failed: " + connectionResult);
}
})
.addApi(Wearable.API)
.build();
googleApiClient.connect();
shouldCollect = true;
Log.d(TAG, "Started collecting");
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"WearTrainingWakelock");
wakeLock.acquire();
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SAMPLE_RATE);
mSensorManager.registerListener(this, mGyroscope, SAMPLE_RATE);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (first) {
first_time = System.currentTimeMillis();
first = false;
}
if (shouldCollect) {
long temp1 = System.currentTimeMillis();
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
switch(event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
mAccelerationRecords.add(new AccelerationRecord(x,y,z,timestamp));
recordCount++;
break;
case Sensor.TYPE_GYROSCOPE:
GyroscopeRecord gyro = new GyroscopeRecord(x,y,z,timestamp);
//Clean up debugging output a little
if (recordCount % 10 == 0) {
Log.d(TAG, "Record is: " + gyro.toString());
}
mGyroscopeRecords.add(gyro);
}
//recordCount > maxNumRecords
if (shouldCollect && (System.currentTimeMillis() - first_time >= 5*60*1000)) {
shouldCollect = false;
new Thread(new SendDataToPhoneTask()).start();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//Not used but must be overridden
}
class SendDataToPhoneTask implements Runnable {
#Override
public void run() {
Log.d(TAG, "Ending stream");
try {
List<List<AccelerationRecord>> accelLists =
Lists.partition(mAccelerationRecords, MAX_RECORDS_SENT_AT_ONCE);
List<List<GyroscopeRecord>> gyroLists =
Lists.partition(mGyroscopeRecords, MAX_RECORDS_SENT_AT_ONCE);
/* I know the following two for loops look like they could be
* abstracted into a single generic method, but due to type erasure
* of generics I can't do this with a single polymoprhic method.
*/
for (List<AccelerationRecord> list : accelLists) {
Log.d(TAG, "Sending list of acceleration records...");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
ArrayList<AccelerationRecord> tmp = new ArrayList<AccelerationRecord>(list);
Log.d(TAG, "List is of size: " + tmp.size());
oos.writeObject(tmp);
oos.flush();
oos.close();
byte[] data = baos.toByteArray();
PutDataMapRequest dataMapRequest = PutDataMapRequest.create("/accel-data");
dataMapRequest.getDataMap().putByteArray("/accel", data);
PutDataRequest request = dataMapRequest.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult =
Wearable.DataApi.putDataItem(googleApiClient, request);
}
//Having a bug where a "that's all" message actually beats the
//data to the phone, so we'll just attach the message to the last
//list of data going out
for (int i = 0; i < gyroLists.size(); ++i) {
List<GyroscopeRecord> list = gyroLists.get(i);
Log.d(TAG, "Sending list of gyroscope records...");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oosG = new ObjectOutputStream(baos);
ArrayList<GyroscopeRecord> tmp = new ArrayList<GyroscopeRecord>(list);
Log.d(TAG, "List is of size: " + tmp.size());
oosG.writeObject(tmp);
oosG.flush();
oosG.close();
byte[] data = baos.toByteArray();
PutDataMapRequest dataMapRequest = PutDataMapRequest.create("/gyro-data");
dataMapRequest.getDataMap().putByteArray("/gyro", data);
if ((i+1) == gyroLists.size()) {
dataMapRequest.getDataMap().putString("/done", DATA_COLLECTION_DONE);
} else {
dataMapRequest.getDataMap().putString("/done", "/not-done");
}
PutDataRequest request = dataMapRequest.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult =
Wearable.DataApi.putDataItem(googleApiClient, request);
}
//Vibrate and tell the user to check their phone
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(500L); //Vibrate for half a second
runOnUiThread(new Runnable() {
#Override
public void run() {
mPrompt.setText("Please finish the training by opening your phone.");
mProgress.setText("");
}
});
} catch (IOException e) {
Log.d(TAG, "Something fucky happened: " + e.getMessage());
} finally {
//Screen can turn off now.
wakeLock.release();
}
}
}
}

WiFi P2P Add Local Service failure

I am trying to develope basic server app on Android using WiFi P2P and Network Service Discovery.
Unfortunatlly I stucked because I am still not able to add local service to my wifi p2p manager. Every time I am tring to run app onFailure method execute. Cannot find the reason.
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
public class ServerMainActivity extends Activity
{
private IntentFilter mIntentFilter;
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private ServerBroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_main);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new ServerBroadcastReceiver(mManager, mChannel, this);
startRegistration();
}
/** register the BroadcastReceiver with the intent values to be matched */
#Override
public void onResume() {
super.onResume();
mReceiver = new ServerBroadcastReceiver(mManager, mChannel, this);
registerReceiver(mReceiver, mIntentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.server_main, menu);
return super.onCreateOptionsMenu(menu);
}
private void startRegistration() {
mManager.clearLocalServices(mChannel, new ActionListener() {
#Override
public void onFailure(int arg0) {
Log.d("Server Main Activity", "cannot clear local services " + arg0);
}
#Override
public void onSuccess() {
// TODO Auto-generated method stub
Log.d("Server Main Activity", "local services cleared.");
// Create a string map containing information about your service.
Map<String,String> record = new HashMap<String,String>();
record.put("listenport", "0");
record.put("buddyname", "John Doe" + (int) (Math.random() * 1000));
record.put("available", "visible");
// Service information. Pass it an instance name, service type
// _protocol._transportlayer , and the map containing
// information other devices will want once they connect to this one.
WifiP2pDnsSdServiceInfo serviceInfo =
WifiP2pDnsSdServiceInfo.newInstance("_SynchroMusic", "_tcp", record);
// Add the local service, sending the service info, network channel,
// and listener that will be used to indicate success or failure of
// the request.
mManager.addLocalService(mChannel, serviceInfo, new ActionListener() {
#Override
public void onSuccess() {
// Command successful! Code isn't necessarily needed here,
// Unless you want to update the UI or add logging statements.
Log.d("Server Main Activity", "local servica added.");
}
#Override
public void onFailure(int arg0) {
// Command failed. Check for P2P_UNSUPPORTED, ERROR, or BUSY
Log.d("Server Main Activity", "faliture" + arg0);
}
});
}
});
}
}
Most of this code is based on official android developer tutorials, so I guess it should work. Running cyanogenmod 11 (Android 4.4.2) on HTC One X.
Here is my BroadcastReceiver class if needed:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.util.Log;
public class ServerBroadcastReceiver extends BroadcastReceiver {
public ServerBroadcastReceiver() {
}
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private ServerMainActivity mActivity;
public ServerBroadcastReceiver(WifiP2pManager manager, Channel channel,
ServerMainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Determine if Wifi P2P mode is enabled or not, alert
// the Activity.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
//activity.setIsWifiP2pEnabled(true);
Log.d("ServerBroadcast", "Wifi on");
} else {
//activity.setIsWifiP2pEnabled(false);
Log.d("ServerBroadcast", "Wifi off");
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// The peer list has changed! We should probably do something about
// that.
Log.d("ServerBroadcast", "peers Changed action");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Connection state changed! We should probably do something about
// that.
Log.d("ServerBroadcast", "Con Changed");
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
//fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
/// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
Log.d("ServerBroadcast", "Dev Changed");
}
//throw new UnsupportedOperationException("Not yet implemented " + action);
else throw new UnsupportedOperationException("Not yet implemented " + action);
}
}
When line
//throw new UnsupportedOperationException("Not yet implemented " + action);
is not commented it throws an error
Not yet implementedandroid.net.wifi.p2p.STATE_CHANGED
You must wait for WIFI_P2P_STATE_ENABLED and then register your service.

WifiManager sets SSID passed as Disabled instead of Connecting

I have some code that is supposed to take the SSID passed via an extra in the intent and connect to it, currently it just sets the ones I pass to it as disabled. All of the SSID's im trying to pass have already been connected to before. I' m not sure if its cause there is already an existing network configuration with the SSID, but it may have something to do with it...
package com.wt.checkin;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
#SuppressWarnings("static-access")
#Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
WifiConfiguration tmpConfig = new WifiConfiguration();
tmpConfig.SSID = extras.getString("SSID");
tmpConfig.status = WifiConfiguration.Status.ENABLED;
int netId = wifiMan.addNetwork(tmpConfig);
wifiMan.enableNetwork(netId, true);
}
}
Here is the working code:
package com.wt.checkin;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
#SuppressWarnings("static-access")
#Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}**
WifiConfiguration Config = new WifiConfiguration();
WifiInfo Info = wifiMan.getConnectionInfo();
String SSID = extras.getString("SSID");
Config.SSID = "\"" + SSID+"\"";
wifiMan.addNetwork(Config);
List<WifiConfiguration> list = wifiMan.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
wifiMan.disconnect();
wifiMan.enableNetwork(i.networkId, true);
wifiMan.reconnect();
break;
}
}
}
}
For others experiencing a similar problem I would like to post this related question: How do I connect to a specific Wi-Fi network in Android programmatically?
The OP looks to be doing something very similar and I notice a difference with:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wm.disconnect(); //not in OP
wm.enableNetwork(i.networkId, true);
wm.reconnect(); //not in OP
break;
}
}
I marked the lines that I think should be added. It looks like you have to format the SSID in a very specific way as well which is outlined in the other SO thread.

how to Send Text Messages (SMS) From Android When Near A Predefined Location

Send Text Messages (SMS) From Android When Near A Predefined Location...
Ex. i enter in the college or out from the college that time my Android device check my current position if it match with predefine position then my device send automatic sms to other no.
Any buddy have idea or code related to this ..
thank you..
I put whole code from my SMS util. You should have a look at sendSms function. The util allows you to watch for incoming sms and track sms sent by you ( If you want to do that ).
The next part is to handle location updates. The best way how to do it depends on many things. You can obtain location via LocatinProviders ( GPS, wireless or passive ) or read cell info from TelephonyManager. Below you have some details about them:
LocationProvider:
returns geo lat/lon data
you can not read data if user disabled "Use GPS satellites" and "User wireless networks"
you will rather not get data if you are in a building ( no GPS signal there ).
you have to wait very long for the location.
very good accuracy.
can drain battery a lot.
"pasive" provider can be a good choice for you.
Cells.
returns the neighboring cell information of the device.
location is not available if your device is not connected to gsm/cdma network ( no sim card ).
not good accuracy but rather for you purpose will be ok.
doesn't kill battery so much.
Which option is better for you ?
package android.commons;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
public final class SmsModem extends BroadcastReceiver {
private static final String SMS_DELIVER_REPORT_ACTION = "android.commons.SMS_DELIVER_REPORT";
private static final String SMS_DELIVER_REPORT_TOKEN_EXTRA = "token";
private static final String TAG = SmsModem.class.getSimpleName();
private final Context context;
private final SmsManager smsManager;
private final SmsModemListener listener;
private final Map<String, Integer> pendingSMS = new HashMap<String, Integer>();
public interface SmsModemListener {
public void onSMSSent(String token);
public void onSMSSendError(String token, String errorDetails);
public void onNewSMS(String address, String message);
}
public SmsModem(Context c, SmsModemListener l) {
context = c;
listener = l;
smsManager = SmsManager.getDefault();
final IntentFilter filter = new IntentFilter();
filter.addAction(SMS_DELIVER_REPORT_ACTION);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
context.registerReceiver(this, filter);
}
public void sendSms(String address, String message, String token) {
if ( message != null && address != null && token != null) {
final ArrayList<String> parts = smsManager.divideMessage(message);
final Intent intent = new Intent(SMS_DELIVER_REPORT_ACTION);
intent.putExtra(SMS_DELIVER_REPORT_TOKEN_EXTRA, token);
final PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final ArrayList<PendingIntent> intents = new ArrayList<PendingIntent>();
for ( int i = 0 ; i < parts.size() ; i++ ) {
intents.add(sentIntent);
}
pendingSMS.put(token, parts.size());
smsManager.sendMultipartTextMessage(address, null, parts, intents, null);
}
}
public void clear() {
context.unregisterReceiver(this);
}
#Override
public void onReceive(Context c, Intent intent) {
final String action = intent.getAction();
if ( action.equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i<pdusObj.length; i++) {
messages[i] = SmsMessage.createFromPdu ((byte[]) pdusObj[i]);
final String address = messages[i].getDisplayOriginatingAddress();
final String message = messages[i].getDisplayMessageBody();
listener.onNewSMS(address, message);
}
}
} else if ( action.equalsIgnoreCase(SMS_DELIVER_REPORT_ACTION)) {
final int resultCode = getResultCode();
final String token = intent.getStringExtra(SMS_DELIVER_REPORT_TOKEN_EXTRA);
Log.d(TAG, "Deliver report, result code '" + resultCode + "', token '" + token + "'");
if ( resultCode == Activity.RESULT_OK ) {
if ( pendingSMS.containsKey(token) ) {
pendingSMS.put(token, pendingSMS.get(token).intValue() - 1);
if ( pendingSMS.get(token).intValue() == 0 ) {
pendingSMS.remove(token);
listener.onSMSSent(token);
}
}
} else {
if ( pendingSMS.containsKey(token) ) {
pendingSMS.remove(token);
listener.onSMSSendError(token, extractError(resultCode, intent));
}
}
}
}
private String extractError(int resultCode, Intent i) {
switch ( resultCode ) {
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
if ( i.hasExtra("errorCode") ) {
return i.getStringExtra("errorCode");
} else {
return "Unknown error. No 'errorCode' field.";
}
case SmsManager.RESULT_ERROR_NO_SERVICE:
return "No service";
case SmsManager.RESULT_ERROR_RADIO_OFF:
return "Radio off";
case SmsManager.RESULT_ERROR_NULL_PDU:
return "PDU null";
default:
return "really unknown error";
}
}
}

Categories

Resources