Following will give me basic wifi information, but I want the hardware information:
WiFiScanReceiver.java
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
systemInfo systemInfo;
public WiFiScanReceiver(systemInfo systemInfo) {
super();
this.systemInfo = systemInfo;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = systemInfo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level,
result.level) < 0) bestSignal = result;
}
String message = String.format(
"%s networks found. %s is the strongest.", results.size(),
bestSignal.SSID);
Toast.makeText(systemInfo, message, Toast.LENGTH_LONG).show();
Log.d(TAG, "onReceive() message: " + message);
}
}
systemInfo.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class systemInfo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null) receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
System.out.println("availableMegs:::::::::::" + availableMegs);
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
wifi.startScan();
String ab = getInfo();
System.out.println("CPU INFORMATON:::::::::::::\n" + ab);
textStatus.append("CPU INFORMATON:::::::::::::\n" + ab);
}
}
private String getInfo() {
StringBuffer sb = new StringBuffer();
sb.append("abi: ").append(Build.CPU_ABI).append("\n");
if (new File("/proc/cpuinfo").exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
"/proc/cpuinfo")));
String aLine;
while ((aLine = br.readLine()) != null) {
sb.append(aLine + "\n");
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
permissions are
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This gives me basic wifi information .But I want the hardware information ..
One important difference is the CPU architecture. Although almost all Android devices use ARM CPU, it comes with different versions, including armv5, armv5te, armv6, armv6 with VFP, armv7, armv7 with VFP, armv7 with neon etc.
If your question is how to obtain the hardware information about the WiFi chip, then answer is simple: Android does not provide this kind of data, except of MAC address (which, btw, is not really the hardware information).
Related
I'm building an Android Wear service which runs in the background and logs device data every three minutes. For this logging, I am using a Handler, which records the values and then has an interval of three minutes. This will be used to monitor user behaviour for one month, and as such it should not randomly stop.
I have also used android.intent.action.BOOT_COMPLETED in my manifest and this successfully runs the application whenever the watch is booted.
My issue is that the service can run correctly for 12 hours...and then just suddenly stop. The amount of time appears to be non-deterministic, as sometimes it will stop after 40 minutes. I suspect it's being killed by Android, but in this case I would like it to restart. I have included return START_STICKY in my service and this should minimise the chance of it being killed.
In some solutions, I have seen onDestroy() overridden and a refresh broadcast being sent to the service. While this appears to work, the onDestroy() function is being called every time the Handler completes one piece of work. This leads to the service restarting every three minutes, rather than when the application is actually killed by Android.
I have also looked at the intent actions to see whether my service could be called at regular intervals. However, aside from android.intent.action.BOOT_COMPLETED, all the useful ones cannot be registered in the Manifest file. Since the service will not be running, registerReceiver() would serve little purpose.
Does anybody know of a technique to either a) guarantee a service will not be killed by Android; or b) guarantee that a service will always be restarted after it has been killed. Any help would be greatly appreciated, as I've even started considering writing a Cron job on the device and setting it to execute my app every three minutes! I've also looked at the AlarmManager class, but I fear it is as likely to be killed if running for long periods.
Please find my code below: (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.study">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<receiver android:name="com.example.study.MyServiceManager" android:enabled="true">
<intent-filter>
<action android:name="com.example.study.RestartAction" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name="com.example.study.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.study.RecordService"
android:exported="false" />
</application>
</manifest>
RecordService.java
package com.example.study;
import android.Manifest;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import com.google.android.gms.location.LocationServices;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import com.google.android.gms.location.*;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class RecordService extends IntentService {
private static Context context;
private final static int INTERVAL = 1000 * 5; // 1 minutes
Handler handler = new Handler();
Location myLocation;
private FusedLocationProviderClient mFusedLocationClient;
SensorManager sensorManager;
SensorManager gyroSensorManager;
SensorManager compassSensorManager;
SensorEventListener sensorEventListener;
float[] accValues;
float[] gyroValues;
float[] compassValues;
Runnable handlerTask = new Runnable() {
#Override
public void run() {
try {
recordData();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.postDelayed(handlerTask, INTERVAL);
}
};
public RecordService() {
super("RecordService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
handlerTask.run();
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
public void recordData() throws ExecutionException, InterruptedException {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainActivity.getAppContext());
boolean fineLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean coarseLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean isLocationEnabled = isLocationEnabled(this);
if(fineLocationGranted && coarseLocationGranted && isLocationEnabled) {
long startTime = System.currentTimeMillis();
long timeWaiting = 0L;
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(MainActivity.getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
myLocation = location;
} else {
System.out.print("");
}
}
});
do {
timeWaiting = System.currentTimeMillis() - startTime;
} while (myLocation == null && timeWaiting < 200);
}
List<PackageInfo> packages = getPackageManager().getInstalledPackages(PackageManager.GET_PERMISSIONS);
KeyguardManager kg = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean isLocked = kg.isDeviceSecure();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
gyroSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
compassSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accValues = sensorEvent.values;
} else if(sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE){
gyroValues = sensorEvent.values;
} else if(sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
compassValues = sensorEvent.values;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {}
};
try {
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
gyroSensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL);
compassSensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
} catch(SecurityException e) {
e.printStackTrace();
}
long startTime2 = System.currentTimeMillis();
long timeWaiting2 = 0L;
do {
timeWaiting2 = System.currentTimeMillis() - startTime2;
} while((accValues == null || gyroValues == null || compassValues == null) && timeWaiting2 < 200);
StringBuilder builder = new StringBuilder();
builder.append("G" + (isLocationEnabled ? 1 : 0));
builder.append(" L" + (isLocked ? 1 : 0));
if(accValues != null && gyroValues != null && compassValues != null) {
builder.append(" ACX" + accValues[0]);
builder.append(" ACY" + accValues[1]);
builder.append(" ACZ" + accValues[2]);
builder.append(" GYX" + gyroValues[0]);
builder.append(" GYY" + gyroValues[1]);
builder.append(" GYZ" + gyroValues[2]);
builder.append(" CMX" + gyroValues[0]);
builder.append(" CMY" + gyroValues[1]);
builder.append(" CMZ" + gyroValues[2]);
}
if(myLocation != null) {
builder.append(" LT" + myLocation.getLatitude());
builder.append(" LN" + myLocation.getLongitude());
}
builder.append("\n");
for(PackageInfo info: packages) {
int lastDot = info.packageName.lastIndexOf('.');
builder.append(info.packageName + "\n");
if(info.requestedPermissions != null) {
for (String rqprm : info.requestedPermissions) {
int dot = rqprm.lastIndexOf('.');
builder.append(rqprm.substring(dot != -1 ? dot + 1 : 0) + " ");
}
builder.append("\n");
for (int permflag : info.requestedPermissionsFlags) {
builder.append("" + permflag + " ");
}
builder.append("\n");
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd--HH-mm-ss");
String currentDateString = sdf.format(new Date());
File log = new File("/sdcard/Recordings/" + currentDateString);
try {
if (!log.exists()) {
log.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
writer.append(builder.toString());
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
MainActivity.java
package com.example.study;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
private static Context context;
private static MainActivity activity;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.context = getApplicationContext();
activity = this;
serviceIntent = new Intent(this, RecordService.class);
startForegroundService(serviceIntent)
startService(serviceIntent);
}
public static Context getAppContext() {
return MainActivity.context;
}
public static MainActivity getActivity() {
return activity;
}
}
MyServiceManager.java
package com.example.study;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class MyServiceManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
}
I need help with that, i found one more same question but didnt work for me.
Thats my code:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CallDetector extends Service {
static String[] test = new String[15];
boolean isstart = false;
AudioManager audio_mng;
private static final String DEBUG_TAG = "InviteActivity";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
CallDetector calldetector= new CallDetector(this);
Log.v(DEBUG_TAG, "Service start");
int i = 0;
File file = new File("pathtofile/myfile.txt");
try {
Scanner scaner = new Scanner(new FileReader(file));
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
do{
line = scaner.nextLine();
test[i] = line;
i++;
br.close();
}while(scaner.hasNext());
}
catch (IOException e) {
//You'll need to add proper error handling here
}
calldetector.start();
return START_STICKY;
}
public void onDestroy(){
CallDetector calldetector = new CallDetector(this);
calldetector.stop();
super.onDestroy();
}
public void onCreate(){
super.onCreate();
audio_mng = (AudioManager) getBaseContext().getSystemService(ctx.AUDIO_SERVICE);
}
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
for(int i =0; i <15; i++) {
if (incomingNumber.equals(test[i])) {
Log.v(DEBUG_TAG, "OK");
onchangetonormal();
}
}
}
}
}
private Context ctx;
private TelephonyManager tm;
private PhoneCallListener callStateListener;
public void onchangetonormal(){
audio_mng.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
public CallDetector(Context ctx) {
this.ctx = ctx;
callStateListener = new PhoneCallListener();
}
/**
* Start calls detection.
*/
public void start() {
Log.v(DEBUG_TAG, "Start listening");
tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* Stop calls detection.
*/
public void stop() {
tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
}
}
when i get a call with service running i get the error but the service keep running.
In my first code was this:
if (TelephonyManager.CALL_STATE_RINGING == state) {
for(int i =0; i <15; i++) {
if (incomingNumber.equals(test[i])) {
Log.v(DEBUG_TAG, "OK");
AudioManager audio_mng;
audio_mng = (AudioManager) getBaseContext().getSystemService(ctx.AUDIO_SERVICE);
audio_mng.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}
}
All was in the if for when the phone get a call !
I found a solution as i said and i try to put them in onCreat and then call it in if but nothing.
Edit:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.test.testapp.CallDetector.onchangetonormal(CallDetector.java:156)
at com.test.testapp.CallDetector$PhoneCallListener.onCallStateChanged(CallDetector.java:107)
at android.telephony.PhoneStateListener$2.handleMessage(PhoneStateListener.java:393)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
Thanks!
And sorry for my bad english !
As in log NullPointerException exception occur in onchangetonormal method means audio_mng is null.
Put null check before using audio_mng object in onchangetonormal method:
if(audio_mng==null){
audio_mng=(AudioManager)CallDetector.this.getSystemService(
Context.AUDIO_SERVICE);
}
I have an idea today....
To declare AudioManager audio_mng as static....
That works !
If you have other explanation or another answer or why that happened please answer.
Thank you for your interest
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.
For some reason it doesn't like the getInetAddresses() method in the lines:
Enumeration additions = (Enumeration) ev.getInfo().getInetAddresses();
if (ev.getInfo().getInetAddresses() != null && ev.getInfo().getInetAddresses().length > 0) {
additions = ev.getInfo().getInetAddresses()[0].getHostAddress();
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import javax.jmdns.ServiceInfo;
private String type = "_workstation._tcp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
Enumeration additions = (Enumeration) ev.getInfo().getInetAddresses();
if (ev.getInfo().getInetAddresses() != null && ev.getInfo().getInetAddresses().length > 0) {
additions = ev.getInfo().getInetAddresses()[0].getHostAddress();
}
notifyUser("Service resolved: " + ev.getInfo().getQualifiedName() + " port:" + ev.getInfo().getPort() + additions);
}
#Override
public void serviceRemoved(ServiceEvent ev) {
notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_test._tcp.local.", "AndroidTest", 0, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
Try download and use latest version of JmDNS from Maven Central Repository, apparently there are some issues related to the jar file downloaded from their SourceForge home page. jar file from SourceForge doesn't play quite nice with Android.
Check out this SO question for more details. Hope this help.
I'm trying to write an android app for may Nexus S that is able to write a simple Text Record on a NFC-Tag. My problem is the connection-establishment to the NFC-Tag.
I've implemented two activities called "TagWriter" & "TagWriterStartPage".
Here ist the "TagWriter"-activity:
package nfc.example.writer;
import java.util.Locale;
import com.google.common.base.Charsets;
import com.google.common.primitives.Bytes;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TagWriter extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tagwriter);
Intent intent = this.getIntent();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(tag);
}
private void writeTag(Tag t)
{
Ndef tag = Ndef.get(t);
Locale locale = Locale.US;
final byte[] langBytes = locale.getLanguage().getBytes(Charsets.US_ASCII);
String text = "Tag, you're it!";
final byte[] textBytes = text.getBytes(Charsets.UTF_8);
final int utfBit = 0;
final char status = (char) (utfBit + langBytes.length);
final byte[] data = Bytes.concat(new byte[] {(byte) status}, langBytes, textBytes);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
try
{
NdefRecord[] records = {record};
NdefMessage message = new NdefMessage(records);
tag.connect();
boolean connected = tag.isConnected();
boolean writeable = tag.isWritable();
if( connected && writeable)
{
tag.writeNdefMessage(message);
}
tag.close();
}
catch (Exception e)
{
//do error handling
}
}
}
The activity "TagWriter" is called when I put my device on the NFC-tag. Everytime the method "tag.connect()" is called, there occures an exception.
Can anyone help me to solve the problem???
Thanks,
Dennis
this might work better:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
format.connect();
format.format(message);
}
}
need other checks in there for real use (capacity, writable etc) - but that is bare bones..