martedì 10 settembre 2013

Creazione di post automatici su Facebook con RFID su Android (7)



Qui viene descritto come pubblicare su Facebook in modo automatico mediante un telefono abilitato con Rfid. In pratica si tratta dell'unione di diversi post precedenti ed in particolare questo e questo


A differenza di Java, per creare una connessione Http in Android si devono prima settare i permessi nel file Manifest.xml (come al solito le modifiche rispetto ai post precedenti sono in giallo)


Manifest.xml
---------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test4"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.NFC"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.test4.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>


        <activity android:label="@string/event_verify" android:name="verifytagscanact">
            <intent-filter>
                <action android:name="android.nfc.action.TECH_DISCOVERED"/>
            </intent-filter>
            <meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/filter_nfc"/>
        </activity>

    </application>

</manifest>
---------------------------------------------------

Nella main le modifiche sono minime e piuttosto simili a Java per l'oggetto HttpConnection. Molto peculiari sono le prime righe dopo OnCreate perche' sono relative ad una gestione specifica di Android (come si puo' leggere meglio spiegato in questo post)

MainActivity.java
---------------------------------------------------
package com.example.test4;

import android.os.Bundle;
import android.app.Activity;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.nfc.Tag;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.widget.Toast;
import java.math.BigInteger;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity {

    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    String[][] techListsArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.
        ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        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_TECH_DISCOVERED);
        try {
            tagDetected.addDataType("*/*");
        }
        catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };

        techListsArray = new String[][] { new String[] { MifareClassic.class.getName() } };

    }

    static String bin2hex(byte[] data) {
        return String.format("%0" + (data.length * 2) + "X", new BigInteger(1,data));
    }

    @Override
    protected void onNewIntent(Intent intent){
        //Toast.makeText(getApplicationContext(), "Trovato Tag", Toast.LENGTH_SHORT).show();
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);


        // trasmissione dati al server
      try {
            URL url = new URL("http://m.msn.unifi.it/luca/examples/rfid_server3.php?rfid="+bin2hex(tag.getId())+"&msg=cellulare");
            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();

            readStream(connection.getInputStream());
            Toast.makeText(getApplicationContext(), bin2hex(tag.getId()), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
            e.printStackTrace();
              }
    

    }


 private void readStream(InputStream in) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    public void onPause() {
        super.onPause();
        adapter.disableForegroundDispatch(this);
    }

    public void onResume() {
        super.onResume();
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, techListsArray);
    }


    @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;
    }
    
}

---------------------------------------------------
deve essere infine modificato il file /res/values/strings.xml


il file sul server e' identico a quello usato in precedenza

Nessun commento:

Posta un commento

Riparazione volante Logitech G920

Con il tempo la pedaliera del Logitech G920 ha cominciato a fare i capricci in particolare per quanto riguarda l'acceleratore Ho provato...