I've managed to make a NFC application in which when the specific tag is scanned, the phone will automatically establish connection with one particular Wi-Fi. (even if Wi-Fi is off) I've already included the SSID and password in the code(tag) so the users can just scan the tag to connect. However, I notice that on my first tap, Wi-Fi is enabled(if disabled) but it will not connect to the Wi-Fi. Only on the second tap, it connects to the specified Wi-Fi. Why is it so?
My code:
#Override
protected void onNewIntent(Intent intent) {
String result2="";
String resultid="";
String resultpw="";
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
/*
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 0; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
*/
try{
//grabbing 2nd payload
byte[] payload2 = messages[0].getRecords()[1].getPayload();
for (int test = 0; test<payload2.length; test++) { // skip SOH
result2 += (char) payload2[test];
//Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();
}
}
catch(ArrayIndexOutOfBoundsException e){
Toast.makeText(getApplicationContext(), "Wrong tag detected. Try again!", Toast.LENGTH_SHORT).show();
}
//grab ssid
try{
byte[] payload3 = messages[0].getRecords()[2].getPayload();
for (int test = 0; test<payload3.length; test++) { // skip SOH
resultid += (char) payload3[test];
//Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();
}
}
catch(ArrayIndexOutOfBoundsException e){
}
//grab ssid_pw
try{
byte[] payload4 = messages[0].getRecords()[3].getPayload();
for (int test = 0; test<payload4.length; test++) { // skip SOH
resultpw += (char) payload4[test];
//Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();
}
}
catch(ArrayIndexOutOfBoundsException e){
}
if (result2.contains("StarbucksBestCoffee"))
{
final ImageView img = (ImageView)findViewById(R.id.imageView1);
/* Call to convert bytes to hex .
*
String uid = toHex(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
Toast.makeText(this, uid, Toast.LENGTH_LONG).show();*/
/*if (storedPreference!=10)
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
img.invalidate();
}*/
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
img.invalidate();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
img.invalidate();
}
});
builder.show();
}
else
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
editor.commit();
img.setImageResource(images[storedPreference]);
img.invalidate();
}
if (resultid!=null&&resultpw!=null)
{
//Wi-Fi Manager auto-connect
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + resultid + "\"";
wc.preSharedKey = "\"" + resultpw + "\"";
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifi.addNetwork(wc);
Log.d("WifiPreference", "add Network returned " + res );
boolean b = wifi.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b );
wifi.setWifiEnabled(true);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
Try this:
Process the NDEF message in 'onResume', and
Add the Wifi when wifi is enabled
In other words, if wifi is not enabled,
Store the wifi credentials,
Listen for Wifi broadcasts untill enabled, then
Add the network
Also, your NDEF parsing is a real hack. Try if parsing using this works instead.
Related
I am doing an application that can read nfc and then treat the content message but I only want certain people to be able to read the tag. So in a way I would like the user to scan the tag and be prompted for a password before being able to read the tag. Is this possible ?
Open to any ideas. It is also possible to keep only the read mode and change the write mode to kind of writing password on the tag to secure it.
btnWrite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
try {
if(myTag ==null) {
Toast.makeText(context, ERROR_DETECTED, Toast.LENGTH_LONG).show();
} else {
write(message.getText().toString(), myTag);
Toast.makeText(context, WRITE_SUCCESS, Toast.LENGTH_LONG ).show();
}
} catch (IOException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
}
}
});
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };
}
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
// String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
// Get the Text
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText(text+"\n( taille de la trame: " + text.length () +")");
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
Ndef ndef = Ndef.get(tag);
// Enable I/O
ndef.connect();
// Write the message
ndef.writeNdefMessage(message);
// Close the connection
ndef.close();
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
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];
// set status byte (see NDEF spec for actual bits)
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;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
readFromIntent(intent);
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
nfcAdapter.disableForegroundDispatch(this);
}
}
You can have the password implementation either in the readFromIntent replacing the buildTagViews(msgs); with checkPasswordDialog(msgs)
private void readFromIntent(Intent intent) {
.....
.... checkPasswordDialog(msgs)
...
In the checkPasswordDialog(NdefMessage[] msgs), you check the password, if it is correct,then continue with buildTagViews(msgs); else, show error.
Or in the buildTagViews(msgs); itself, right before you display the message, the password then determines what you will display, the NFC message or an error( non-authorized user).
Assume I write a function called checkForPasswordDailog() thats asks a user for a password. If the password entered by user is correct then continue to display the messege otherwise display and unauthorised user messege. i.e
protected void checkForPasswordDialog(NdefMessage[] msgs){
/*create a dialog view with either both usename
and password or just a password if every user uses the same
password*/
MaterialDialog(this).show{
// add a title
View passwordDialogView = customView(R.layout.password_dialog_view)
//when the user submits their inputs
Textview userNameView = passwordDialogView.findViewById(R.id.username)
Textview passwordView = passwordDialogView.findViewById(R.id.password)
Button submitButton = passwordDialogView.findViewById(R.id.submit_button)
submitButton.setOnClickListener{
if(verifyUser(username.text, password.text)){
buildTagViews(msgs)
cancel()
}else{
showUnauthorizedUserError()
cancel()
}
}
}
protected boolean verifyUser(String username, String password){
//Verify user input
}
protected void showUnauthorizedUseError(){
//Display your message here Snackbar/Dialog e.t.c
}
And your xml file should include
<TextView id = "#+id/username"/>
<TextView id = "#+id/password"/>
<Button id = "#+id/submit_button"/>
Hopefully this helps
I'm trying to write a code I can write all the results values from accelerometer sensor into a .txt file. I can't write all the data in somehow. I think there is a problem in my loop. It is just reading about 10 to 15 samples.
How can I write all the values of the sensor into that file until I toggle off the button to stop? here is the code I wrote.
Thanks in advance!
public class MainActivity extends Activity implements SensorEventListener {
public SensorManager sm;
Sensor accelermeter;
private static final String DEBUG = "LogAccelermeter";
ToggleButton OnStore;
Button OffStore;
Button btnOn, btnOff;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
TextView sensorText;
// String for MAC address
private static String address;
private GestureDetectorCompat mDetector;
FileOutputStream fileOutputStream;
double TotalAccelerate;
ArrayList<Double> list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<Double>();
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
//for Accelermeter
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter, SensorManager.SENSOR_DELAY_NORMAL);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath() + "/MyApp");
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, "MyMessage.txt");
try {
fileOutputStream = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SDcard not found", Toast.LENGTH_LONG).show();
}
OnStore = (ToggleButton) findViewById(R.id.onStore);
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
// System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
// fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fileOutputStream.close();
list.clear();
Collections.synchronizedList(list);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}//end OnCreate Method
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
//Find peak values.
public static ArrayList<Double> findPeaks(List<Double> points) {
ArrayList<Double> peaks = new ArrayList<Double>();
if (points == null || points.size() < 1)
return peaks;
Double x1_n_ref = 0.0;
int alpha = 0; //0=down, 1=up.
int size = points.size();// -1)/100;
for (int i = 0; i < size; i += 5) {
Double IndexValues = points.get(i);
if (IndexValues > 9) {
Double delta = (x1_n_ref - IndexValues);
if (delta < 0) {
x1_n_ref = IndexValues;
alpha = 1;
} else if (alpha == 1 && delta > 0) {
peaks.add(x1_n_ref);
alpha = 0;
}
} else if (alpha == 0) {
x1_n_ref = IndexValues;
}
}
return peaks;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG, "onDown: " + event.toString());
Toast.makeText(getApplication(), "OnDown Touch Occur", Toast.LENGTH_LONG).show();
if (event.getX() > 0) {
mConnectedThread.write("1");
}
return true;
}
#Override
public void onLongPress(MotionEvent event) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString());
mConnectedThread.write("0");
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
Could you try this for the toggle button onClick callback? It should write all the data when it's unchecked.
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
// should do nothing
} else if (!OnStore.isChecked()){
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
To regulate the code to start/stop listen to the sensor event, add the following variable somewhere in this class:
private boolean isListening = false;
And make the following modifications to your existing code:
OnStore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (OnStore.isChecked()){
//
// set listening flag to true
//
isListening = true;
} else if (!OnStore.isChecked()){
//
// set listening flag to false
//
isListening = false;
try {
for(double TotalAccelerate : list){
//System.out.println("final"+ TotalAccelerate);
String space = "\n";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
Log.i(DEBUG, "ans: " + finalData);
}
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Message saving", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
}
}
});
#Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
//
// regulate
//
if (isListening) {
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
Log.i(DEBUG, "Accelerometer = " + TotalAccelerate);
list.add(TotalAccelerate);
findPeaks(list);
sensorText.setText("Total: " + TotalAccelerate);
Log.i(DEBUG, "list values " + list);
}
}
I would like to send data (string) via USB communication from my Android application to a device. I am beginner in Android development, so I followed this tutorial: http://developer.android.com/guide/topics/connectivity/usb/host.html
Somehow the part Communicating with a device doesn't work, doesn't send any text to the device. I tried to send data also with
connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);
or with
ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);
request.initialize(connection, epOut);
request.queue(buffer, bytes.length);
but nothing worked.
I don't really understand, how could I send a short text for example "#V" to the device from my android app.
Could you please help me find the problem in my code? Thanks in advance.
Here is my MainActivity class:
public class MainActivity extends AppCompatActivity {
UsbDevice device;
Button bShow;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
Boolean isDevice = true;
TextView tvTest;
String sendText = "#V";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
int controlTransferResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTest = (TextView) findViewById(R.id.textView);
showData();
}
public void showData(){
bShow= (Button)findViewById(R.id.button);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Log.e("MainActivity", "DeviceList:" + deviceList.toString());
if(deviceList.toString().equals("{}")){
Toast.makeText(MainActivity.this,"No USB device found!", Toast.LENGTH_SHORT).show();
return;
}else{
tvTest.setText(deviceList.toString());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
//while(deviceIterator.hasNext()) {
device = deviceIterator.next();
//}
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mUsbManager.requestPermission(device, mPermissionIntent);
bShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, device.getDeviceName() + "\n"
+ device.getManufacturerName() + "\n"
+ device.getProductName() + "\n"
+ device.getVendorId() + "\n"
+ device.getDeviceId() + "\n"
+ "i=" + controlTransferResult, Toast.LENGTH_SHORT).show();
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
UsbInterface intf = device.getInterface(0);
UsbEndpoint epOut = null;
UsbEndpoint epIn = null;
// look for our bulk endpoints
for (int i = 0; i < intf.getEndpointCount(); i++) {
UsbEndpoint ep = intf.getEndpoint(i);
//Log.d(TAG, "EP " + i + ": " + ep.getType());
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
epOut = ep;
} else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
epIn = ep;
}
}
}
if (epOut == null || epIn == null) {
throw new IllegalArgumentException("Not all endpoints found.");
}
//UsbEndpoint endpoint = intf.getEndpoint(1);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = sendText.getBytes();
controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);//baudrate 9600
//int res = connection.bulkTransfer(epOut, bytes, bytes.length, TIMEOUT); //do in another thread
ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);
request.initialize(connection, epOut);
request.queue(buffer, bytes.length);
}
}
else {
Log.d("MyActivity", "permission denied for device " + device);
}
}
}
}
};
}
You need to prepare drivers for your Android device first, for example, if your device is using CP210X chipset for USB support you should follow these steps: https://www.silabs.com/documents/public/application-notes/AN809.pdf
After selecting multiple images from a gallery, I want to upload them to an ftp server. During the upload, I get the following error:
"java.io.FileNotFoundException: /storage/emulated/0/DCIM/Camera/IMG_20150724_220209.jpg /storage/emulated/0/DCIM/Screenshots/Screenshot_2015-08-04-14-47-38.png "
Can anyone help?
public class MainActivity extends Activity implements View.OnClickListener{
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE =1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String[] th;
String str;
String picturepath,currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout)findViewById(R.id.lnrImages);
btnAddPhots = (Button)findViewById(R.id.btnAddPhots);
btnSaveImages = (Button)findViewById(R.id.btnSaveImages);
b=(Button)findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,CustomPhotoGalleryActivity.class);
startActivityForResult(intent,PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
if(imagesPathList !=null){
if(imagesPathList.size()>=1) {
File f = new File("" + r);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this," no images are selected", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/real/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/real/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode ==Activity.RESULT_OK
&& null != data) {
//uri=data.getData();
// System.out.println("Current image Path is ----->" + getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
String[] imagesPath = data.getStringExtra("data").split("\\|");
try{
lnrImages.removeAllViews();
}catch (Throwable e){
e.printStackTrace();
}
for (int i=0;i<imagesPath.length;i++){
Log.e("imagesPath can", ""+imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", ""+imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", ""+yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList)
{
listString += s + "\t";
}
j=listString.toString();
uri=Uri.parse(j);
r=uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", ""+r);
Log.d("anananananananananananananananananananananannananand", ""+uri);
}
}
}
private void decodeFile(String picturePath) {
// TODO Auto-generated method stub
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
yourbitmap = BitmapFactory.decodeFile(picturePath, o2);
}}
Public class MainActivity extends Activity implements View.OnClickListener {
private LinearLayout lnrImages;
private Button btnAddPhots;
private Button btnSaveImages;
private ArrayList<String> imagesPathList;
private Bitmap yourbitmap;
private Bitmap resized;
private final int PICK_IMAGE_MULTIPLE = 1;
static final String FTP_HOST = "";
static final String FTP_USER = "";
static final String FTP_PASS = "";
String j;
Uri uri;
String str;
String picturepath, currentpath;
Button b;
String r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lnrImages = (LinearLayout) findViewById(R.id.lnrImages);
btnAddPhots = (Button) findViewById(R.id.btnAddPhots);
btnSaveImages = (Button) findViewById(R.id.btnSaveImages);
b = (Button) findViewById(R.id.btnSaveImages1);
btnAddPhots.setOnClickListener(this);
btnSaveImages.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,
CustomPhotoGalleryActivity.class);
startActivityForResult(intent, PICK_IMAGE_MULTIPLE);
break;
case R.id.btnSaveImages:
//upload multiple images
if (imagesPathList != null) {
if (imagesPathList.size() >= 1) {
for (int i = 0; i < imagesPath.length; i++) {
String strImg = imagesPath[i];
File f = new File("" + strImg);
Log.e("File", "" + f);
doFileUpload(f);
Log.d("saveimages", "" + imagesPathList);
}
Toast.makeText(
MainActivity.this,
imagesPathList.size()
+ " no of images are selected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
MainActivity.this,
imagesPathList.size() + " no of image are selected",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, " no images are selected",
Toast.LENGTH_SHORT).show();
}
break;
}
}
public void doFileUpload(File f) {
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST, 21);
Log.e("clientconnect", "" + client);
client.login(FTP_USER, FTP_PASS);
Log.e("clientlogin", "" + client);
client.setType(FTPClient.TYPE_BINARY);
Log.e("clienttype", "" + client);
client.changeDirectory("/ramesh2/");
Log.i("", "$$$$$$$$$$$$$$$$$" + ("/ramesh2/"));
// int reply = client.getReplyCode();
client.upload(f, new MyTransferListener());
// Log.e("filenameupload", "" + photoFile);
Log.e("clientupload", "" + client);
// Log.e("file",""+fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
// btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getApplicationContext(), " Upload Started ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time
// this
// method was called
Toast.makeText(getApplicationContext(),
" transferred ..." + length, Toast.LENGTH_SHORT).show();
// System.out.println(" transferred ..." + length);
}
public void completed() {
// btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getApplicationContext(), " completed ...",
Toast.LENGTH_SHORT).show();
// System.out.println(" completed ..." );
}
public void aborted() {
// btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getApplicationContext(),
" transfer aborted , please try again...",
Toast.LENGTH_SHORT).show();
// System.out.println(" aborted ..." );
}
public void failed() {
// btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ...");
}
// Jibble.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE
&& resultCode == Activity.RESULT_OK && null != data) {
// uri=data.getData();
// System.out.println("Current image Path is ----->" +
// getRealPathFromURI(uri));
imagesPathList = new ArrayList<String>();
imagesPath = data.getStringExtra("data").split("\\|");
try {
lnrImages.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
for (int i = 0; i < imagesPath.length; i++) {
Log.e("imagesPath can", "" + imagesPath);
imagesPathList.add(imagesPath[i]);
Log.w("imagesPathList are", "" + imagesPathList);
yourbitmap = BitmapFactory.decodeFile(imagesPath[i]);
Log.d("yourbitmap is", "" + yourbitmap);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourbitmap);
imageView.setAdjustViewBounds(true);
lnrImages.addView(imageView);
String listString = "";
for (String s : imagesPathList) {
listString += s + "\t";
}
j = listString.toString();
uri = Uri.parse(j);
r = uri.toString();
Log.d("mnmnmnmnmnmnmhjjuigyigsuiagducfuducgfasicfgds", "" + r);
Log.d("anananananananananananananananananananananannananand",
"" + uri);
}
}
}
I'm developing a multi-player quiz application. I'm using GCM to send messages from my server to the devices. The registration is done by this code
//skeletonactivity.java
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart(): Connecting to Google APIs");
mGoogleApiClient.connect();
regId = registerGCM();
appUtil=new ShareExternalServer();
shareRegidTask = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = appUtil.shareRegIdWithAppServer(context, regId);
return result;
}
#Override
protected void onPostExecute(String result) {
shareRegidTask = null;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
};
shareRegidTask.execute(null, null, null);
Log.d("RegisterActivity", "GCM RegId: " + regId);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent=new Intent(SkeletonActivity.this,Quizform.class);
startActivity(intent);
finish();
}
}, 1000);
// i have tried making the activity launch after sometime, so that the GCM message will be recieved. but there's no change.
}
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("RegisterActivity",
"registerGCM - successfully registered with GCM server - regId: "
+ regId);
}
return regId;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void...Params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: "
+ regId);
msg = "Device registered, registration ID=" + regId;
storeRegistrationId(context, regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
Log.i(TAG, "Saving regId on app version" );
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.commit();
}
The code for sharing with external activity is
shareExternalServer
public class ShareExternalServer {
public String shareRegIdWithAppServer(final Context context,
final String regId) {
String result = "";
Map paramsMap = new HashMap();
paramsMap.put("regId", regId);
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status;
}
} finally {
if (httpCon != null) {
httpCon.disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}
the code for GCMIntentService.java
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
public SharedPreferences sharedPreferences;
public static SharedPreferences getSharedPreferences (Context ctxt) {
return ctxt.getSharedPreferences("message",0);
}
public static boolean flag;
public static final String TAG = "GCM Demo";
public String mess=" ";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
sharedPreferences= getSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType=gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
mess= extras.getString("message");
editor.putString("mess",mess);
editor.commit();
Log.i(TAG, "Received: " + mess);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
The above code gets the value from the broadcast receiver and stores it the string msg.
i try to access it as below in quizform.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); sharedPreferences=getApplicationContext().getSharedPreferences("messages",0);
setContentView(R.layout.activity_quizform);
txt = sharedPreferences.getString("mess","empty");
Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
}
The value of txt is empty, and so i get only a blank toast.
The server sends the message as soon as it gets the regID. the code is:
<?php
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "apikey");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function sendquestions()
{
$servername = " ";
$username = " ";
$password = " ";
$dbname=" ";
$conn = mysqli_connect($servername, $username, $password,$dbname);
$pushStatus = "";
$result= mysqli_query($conn,"SELECT id FROM regid");
while($row = $result->fetch_assoc()){
$gcmRegID=$row['id'];}
$pushMessage = "hello";
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("message" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
//this block is to receive the GCM regId from external (mobile apps)
if(!empty($_GET["shareRegId"]))
{
$gcmRegID = $_POST["regId"];
mysqli_query($conn,"INSERT INTO regid (id) VALUES('$gcmRegID')");
$retval = mysql_query( $mysqli, $conn );
mysqli_close($conn);
sendquestions();
exit;
}
?>
Please do suggest ways to get over the delay . thanks