We are able to list paired Bluetooth devices in a text view.The app has two EditText ,one to accept string message and the other to accept the MAC address of destination device,and one send button to send the message to the destination address, but the app is getting closed when clicked on the send button.Kindly help us.
Thanks in advance.
package com.example.javapoint;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
TextView textview1;
UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter btAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (TextView)findViewById(R.id.textView1);
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
textview1.append("\nAdapter: " + btAdapter);
CheckBluetoothState();
}
/* It is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBluetoothState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void CheckBluetoothState() {
// Checks for the Bluetooth support and then makes sure it is turned on
// If it isn't turned on, request to turn it on
// List paired devices
if(btAdapter==null) {
textview1.append("\nBluetooth NOT supported. Aborting.");
return;
} else {
if (btAdapter.isEnabled()) {
textview1.append("\nBluetooth is enabled...");
// Listing paired devices
textview1.append("\nPaired Devices are:");
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {
textview1.append("\n Device: " + device.getName() + ", " + device);
}
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Button sbtn=(Button)findViewById(R.id.btn2);
final EditText et=(EditText)findViewById(R.id.message);
final String msg=et.getText().toString();
final EditText et1=(EditText)findViewById(R.id.macaddress);
final String mac=et1.getText().toString();
sbtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
byte[] toSend = msg.getBytes();
try {
BluetoothDevice mBluetoothDevice = btAdapter.getRemoteDevice(mac);
BluetoothSocket socket =mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
socket.connect();
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
socket.close();
// Your Data is sent to BT connected paired device ENJOY.
} catch (IOException e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Related
I am working on an app that allows Android and IOS devices to communicate to each other using Bluetooth. My IOS application is working fine, but I cannot get the android application to work. I am trying to make the android device my central. The problem I have encountered is that I am not able to scan for devices as when I do I get this message from the Android monitor:
08-07 15:09:30.983 27349-27364/uk.ac.york.androidtoios2
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=5.
Can someone tell me what is wrong with my code that is not allowing me to scan for the peripheral IOS device.
MainActivity.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothGatt gatt;
private BluetoothGattCharacteristic inputCharacteristic;
private TextView outputView;
private EditText inputView;
private static final int REQUEST_ENABLE_BT = 1;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void receiveMode(View v) {
int apiVersion = android.os.Build.VERSION.SDK_INT;
if (apiVersion >= Build.VERSION_CODES.LOLLIPOP) {
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
// get the discovered device as you wish
// this will trigger each time a new device is found
BluetoothDevice device = result.getDevice();
}
});
} else {
// targeting kitkat or bellow
bluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// get the discovered device as you wish
}
});
}
}
// rest of your code that will run **before** callback is triggered since it's asynchronous
public void sendMessage(View v) {
inputCharacteristic.setValue(inputView.getText().toString());
gatt.writeCharacteristic(inputCharacteristic);
}
BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (getString(R.string.outputUUID).equals(characteristic.getUuid().toString())) {
final String value = characteristic.getStringValue(0);
runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(value);
}
});
}
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
MainActivity.this.gatt = gatt;
if (newState == BluetoothProfile.STATE_CONNECTED) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.discoverServices();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
if (getString(R.string.outputUUID).equals(characteristic.getUuid().toString())) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptors().get(0);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
} else if (getString(R.string.inputUUID).equals(characteristic.getUuid().toString())) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inputCharacteristic = characteristic;
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputView = (TextView) findViewById(R.id.outputText);
inputView = (EditText) findViewById(R.id.inputText);
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
I'm working on a school project and have hit a road block and wanted to see if anyone can help point me in the right direction. We are trying to capture packets from an Android phone without rooting the phone. The only option that I have found was to use Android's VPNService to use it as a middle man to capture the packets.
The idea that I had was to create a button to capture the packets, on a onclick event.
package cybutech.com.datacapture;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.net.VpnService;
import android.preference.PreferenceFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private int capture = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
final Button captureData = (Button)findViewById(R.id.capture);
captureData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (capture == 1) {
captureData.setBackgroundColor(Color.RED);
captureData.setText("Stop Capture!");
Intent intent = VpnService.prepare(getApplicationContext());
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
capture *= -1;
} else {
captureData.setBackgroundColor(Color.GREEN);
captureData.setText("Start!");
capture *= -1;
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, MyVpnService.class);
startService(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
return true;
}
}
package cybutech.com.datacapture;
import android.content.Intent;
import android.net.VpnService;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;
public class MyVpnService extends VpnService {
private Thread mThread;
private ParcelFileDescriptor mInterface;
//a. Configure a builder for the interface.
Builder builder = new Builder();
// Services interface
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start a new session by creating a new thread.
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
//a. Configure the TUN and get the interface.
mInterface = builder.setSession("MyVPNService")
.addAddress("192.168.0.1", 24)
.addDnsServer("8.8.8.8")
.addRoute("0.0.0.0", 0).establish();
//b. Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(
mInterface.getFileDescriptor());
//b. Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
//c. The UDP channel can be used to pass/get ip package to/from server
DatagramChannel tunnel = DatagramChannel.open();
// Connect to the server, localhost is used for demonstration only.
tunnel.connect(new InetSocketAddress("127.0.0.1", 8087));
//d. Protect this socket, so package send by it will not be feedback to the vpn service.
protect(tunnel.socket());
//e. Use a loop to pass packets.
while (true) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while(true) {
String line = reader.readLine();
if (line == null) {
System.out.print("NULLLLLLL");
break;
} else {
System.out.println("line is " + line);
}
// I am guessing that here after reading the packets, I need to forward them to the actual server.
Thread.sleep(100);
}
}
} catch (Exception e) {
// Catch any exception
e.printStackTrace();
} finally {
try {
if (mInterface != null) {
mInterface.close();
mInterface = null;
}
} catch (Exception e) {
}
}
}
}, "MyVpnRunnable");
//start the service
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mThread != null) {
mThread.interrupt();
}
super.onDestroy();
}
}
I'm trying to make an application that writes a simple plain text message to an NFC tag. The user writes a message in the EditText box, then on button press, the app writes the text onto a tag.
I've been following this tutorial: http://www.framentos.com/it/android-tutorial/2012/07/31/write-hello-world-into-a-nfc-tag-with-a/
However, when i try to put the NFC tag up next to it, the phone opens up another app, instead of using mine that is already open. I know the problem's with the intents, but i don't want to declare the intent filter in the manifest, because i don't want the app to open up when the tag is placed next to the phone, i want the app to be already open beforehand.
Here's the code for the application:
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
Tag mytag;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
Button btnWrite = (Button) findViewById(R.id.button);
final EditText message = (EditText)findViewById(R.id.edit_message);
btnWrite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
try {
if(mytag==null){
Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG).show();
}else{
write(message.getText().toString(),mytag);
Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
}
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.error_writing), Toast.LENGTH_LONG ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(ctx, ctx.getString(R.string.error_writing) , Toast.LENGTH_LONG ).show();
e.printStackTrace();
}
}
});
adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
//create the message in according with the standard
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
payload[0] = (byte) langLength;
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
#Override
protected void onNewIntent(Intent intent){
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())){
mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(this, this.getString(R.string.ok_detection) + mytag.toString(), Toast.LENGTH_LONG ).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Please help, i don't know what i'm doing wrong!
I'm just a beginner at NFC and Android programming!
You have to use enable forground dispatch : http://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html#foreground-dispatch
The foreground dispatch system allows an activity to intercept an
intent and claim priority over other activities that handle the same
intent.
UPDATE1
It's difficult to write on all kind of tags, some of them have closed specifications. You could start by writing on Ndef and NdefFormatable tags.
For instance:
#Override
protected void onPause() {
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
#Override
protected void onResume(){
super.onResume();
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
IntentFilter ndef=new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
}
catch ( MalformedMimeTypeException e) {
Log.e(TAG,"Bad MIME type declared",e);
return;
}
IntentFilter[] filters=new IntentFilter[]{ndef};
String[][] techLists=new String[][]{new String[]{Ndef.class.getName()},new String[]{NdefFormatable.class.getName()}};
mNfcAdapter.enableForegroundDispatch(this,pendingIntent,filters,techLists);
}
#Override
protected void onNewIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
for (String tech : techList) {
if (tech.equals(Ndef.class.getName())) {
//write NDEF msg
} else if (tech.equals(NdefFormatable.class.getName())) {
//format and write NDEF msg
}
}
}
Android Wear Java I'm having some trouble finding out how to implement the Wear to Phone call using the Message Api. Can someone give me a simple working example or help me out here?
This is my code for testing...
Wear MainJava
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
public class MessageActivity extends Activity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
// Register the local broadcast receiver
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
MessageReceiver messageReceiver = new MessageReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.v("myTag", "Main activity received message: " + message);
// Display message in UI
mTextView.setText(message);
}
}
}
Wear Listener Service
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
public class ListenerService extends WearableListenerService{
#Override
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals("/message_path")) {
final String message = new String(messageEvent.getData());
Log.v("myTag", "Message path received on watch is: " + messageEvent.getPath());
Log.v("myTag", "Message received on watch is: " + message);
// Broadcast message to wearable activity for display
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
else {
super.onMessageReceived(messageEvent);
}
}
}
and the mobile(phone)
package com.spokengiovannie.messageactivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MessageActivity extends ActionBarActivity
implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient googleClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
// Build a new GoogleApiClient that includes the Wearable API
googleClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect to the data layer when the Activity starts
#Override
protected void onStart() {
super.onStart();
googleClient.connect();
}
// Send a message when the data layer connection is successful.
#Override
public void onConnected(Bundle connectionHint) {
String message = "Hello wearable\n Via the data layer";
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread("/message_path", message).start();
}
// Disconnect from the data layer when the Activity stops
#Override
protected void onStop() {
if (null != googleClient && googleClient.isConnected()) {
googleClient.disconnect();
}
super.onStop();
}
// Placeholders for required connection callbacks
#Override
public void onConnectionSuspended(int cause) { }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
// Unused project wizard code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SendToDataLayerThread extends Thread {
String path;
String message;
// Constructor to send a message to the data layer
SendToDataLayerThread(String p, String msg) {
path = p;
message = msg;
}
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await();
for (Node node : nodes.getNodes()) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await();
if (result.getStatus().isSuccess()) {
Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
} else {
// Log an error
Log.v("myTag", "ERROR: failed to send Message");
}
}
}
}
}
All this code is from a tutorial. When I launch de app on the phone it suppose to change the textView wear text. Someone have a sample or app already made for contact the phone I'm stuck :(.
I think the problem is LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent) in your WearableListenerService. This is a local broadcast which will not be delivered to the phone.
see API doc LocalBroadcastManager
I'm not sure if you figured it by now but for the fresh lads like me this might help.
Add listener service to the respective class, in this example this is the code.
Add this in your Wear's AndroidManifest.xml file.
<service android:name=".ListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
I need to get the information transfered from the NFC READER to my phone to be Arrange in each line wth for eg.Event ID,Event Name,DateTime,Venue.
At the moment when I tap my phone to the reader using my android app,all i get is a string of text.I want to break the text to be able to identify Event Id,EventName,DateTime,Venue to be able to getText seperately for each text to submit to database.
here is my code
package com.techblogon.loginexample;
import java.nio.charset.Charset;
import java.util.Arrays;
import com.techblogon.loginexample.R;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class UserScreen extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback{
private static final int MESSAGE_SENT = 1;
NfcAdapter mNfcAdapter;
TextView mInfoText;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.userscreen);
mInfoText = (TextView) findViewById(R.id.textView);
// Check for available NFC Adapter
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
mInfoText = (TextView) findViewById(R.id.textView);
mInfoText.setText("NFC is not available on this device.");
}
// Register callback to set NDEF message
mNfcAdapter.setNdefPushMessageCallback(this, this);
// Register callback to listen for message-sent success
mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
} #Override
public NdefMessage createNdefMessage(NfcEvent event) {
Time time = new Time();
time.setToNow();
String text = ("Beam me up!\n\n" +
"Beam Time: " + time.format("%H:%M:%S"));
NdefMessage msg = new NdefMessage(
new NdefRecord[] { createMimeRecord("application/com.example.android.beam", text.getBytes()) });
return msg;
}
#Override
public void onNdefPushComplete(NfcEvent arg0) {
// A handler is needed to send messages to the activity when this
// callback occurs, because it happens from a binder thread
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
Log.w ("Sent",mHandler.obtainMessage(MESSAGE_SENT).toString());
}
/** This handler receives a message from onNdefPushComplete */
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SENT:
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
break;
}
}
};
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
// Parses the NDEF Message from the intent and prints to the TextView
void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
mInfoText.setText(new String(msg.getRecords()[0].getPayload()));
}
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
return mimeRecord;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// If NFC is not available, we won't be needing this menu
if (mNfcAdapter == null) {
return super.onCreateOptionsMenu(menu);
}
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(Settings.ACTION_NFCSHARING_SETTINGS);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try this
textView.setText(string1+System.getProperty ("line.separator")+string2);
Edit : Take two string variable like
String string1 = "Hello";
String string2 = "Android";
then
your_textView.setText(string1 + System.getProperty ("line.separator") + string2);
OR
your_textView.setText("Hello" + System.getProperty ("line.separator") + "Android");