Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.app.Activity;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.net.Uri;
- import android.nfc.NfcAdapter;
- import android.os.Build;
- import android.os.Bundle;
- import android.provider.Settings;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import it.stesp.news.R;
- public class NFC extends Activity {
- public static final String TAG_LOG = NFC.class.getName();
- NfcAdapter mNfcAdapter;
- boolean mAndroidBeamAvailable = false;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.nfc_);
- if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) { // NFC isn't available on the device
- Log.i(TAG_LOG, "No NFC");
- } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { // Android Beam file transfer isn't supported
- Log.i(TAG_LOG, "No Android Beam");
- mAndroidBeamAvailable = false;
- } else { // Android Beam file transfer is available, continue
- mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
- mAndroidBeamAvailable = true;
- }
- Button btn_nfc = (Button) findViewById(R.id.btn_nfc);
- btn_nfc.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- sendFile();
- }
- });
- }
- private void sendFile() {
- if (mAndroidBeamAvailable) {
- // Check whether NFC is enabled on device
- if (!mNfcAdapter.isEnabled()) {
- // NFC is disabled, show the settings UI
- // to enable NFC
- Toast.makeText(this, "Please enable NFC.",
- Toast.LENGTH_SHORT).show();
- startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
- }
- // Check whether Android Beam feature is enabled on device
- else if (!mNfcAdapter.isNdefPushEnabled()) {
- // Android Beam is disabled, show the settings UI
- // to enable Android Beam
- Toast.makeText(this, "Please enable Android Beam.",
- Toast.LENGTH_SHORT).show();
- startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
- } else {
- // NFC and Android Beam both are enabled
- File fileToTransfer = getDummyFile();
- mNfcAdapter.setBeamPushUris(
- new Uri[]{Uri.fromFile(fileToTransfer)}, this);
- Log.i(TAG_LOG, "Uri push");
- }
- }
- }
- private File getDummyFile() {
- File dir = getExternalFilesDir(null);
- if (!dir.exists()) dir.mkdirs();
- String filename = "dummy.txt";
- File file = new File(dir, filename);
- try {
- String text = "prova";
- FileOutputStream out = new FileOutputStream(file);
- out.write(text.getBytes());
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return file;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement