android nfc写入应用程序包名与网址 自动打开应用程序与网址

来源:互联网 发布:java网上商城系统 编辑:程序博客网 时间:2024/05/16 14:37

       安卓手机大部分手机提供了NFC芯片   可以根据NFC传递数据   NFC卡与手机  手机与手机数据等交互  非常好的功能,这篇文章教大家如何向NFC卡或标签写入功能。

       DEMO下载地址http://download.csdn.net/detail/u012303938/9243233

       用法 :  点击包名   将NFC标签靠近手机后置摄像头附近即可  

       效果 : 第一次靠近  将自己的应用程序包名写入nfc标签,第二次靠近    会自动打开自己写入的应该程序。

       注意几点:

       1、清单文件要加上权限  activity使用singleTop启动模式

       2、NFC主要用到  NdfcAdapter与PendingIntent去建立联系

       3、Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);方法去取nfc里的资源

       代码如下:

package com.example.autonfc;import java.io.IOException;import java.util.ArrayList;import java.util.List;import android.support.v7.app.ActionBarActivity;import android.app.Activity;import android.app.AlertDialog;import android.app.ListActivity;import android.app.PendingIntent;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.net.Uri;import android.nfc.FormatException;import android.nfc.NdefMessage;import android.nfc.NdefRecord;import android.nfc.NfcAdapter;import android.nfc.NfcManager;import android.nfc.Tag;import android.nfc.tech.Ndef;import android.nfc.tech.NdefFormatable;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends Activity implements OnItemClickListener{  private List<String> list;  private NfcAdapter adapters;  private PendingIntent intent;  private String packageName;  private ListView listView1;  private NdefMessage ndefMessage;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView1=(ListView) findViewById(R.id.listView1);        list=new ArrayList<String>();        PackageManager manager=getPackageManager();        List<PackageInfo> PackageInfos= manager.getInstalledPackages(PackageManager.GET_ACTIVITIES);        for(PackageInfo info: PackageInfos){        list.add(info.applicationInfo.loadLabel(manager)+"\n"+        info.packageName);        }        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,         android.R.layout.simple_list_item_1, list);        listView1.setAdapter(adapter);        listView1.setOnItemClickListener(this);                adapters=NfcAdapter.getDefaultAdapter(this);intent=PendingIntent.getActivity(this, 0, new Intent(this,getClass()), 0);    }    @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;    }    @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();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id) {// TODO Auto-generated method stubpackageName=list.get(position);Toast.makeText(this, "选择了"+packageName, Toast.LENGTH_SHORT).show();}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();if(adapters!=null){adapters.enableForegroundDispatch(this, intent, null, null);}}@Overrideprotected void onPause() {// TODO Auto-generated method stubsuper.onPause();if(adapters!=null){adapters.disableForegroundDispatch(this);}}@Overrideprotected void onNewIntent(Intent intent) {// TODO Auto-generated method stubsuper.onNewIntent(intent);Toast.makeText(this, "执行了", Toast.LENGTH_SHORT).show();Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);if(packageName==null){Toast.makeText(this, "请选择包名", Toast.LENGTH_SHORT).show();return;}onWriteNFC(tag);}public void onWriteNFC(final Tag tag){if(tag==null){Toast.makeText(this, "没有找到TAG", Toast.LENGTH_SHORT).show();return;}Toast.makeText(this, "tag有值", Toast.LENGTH_SHORT).show();ndefMessage=new NdefMessage(new NdefRecord[]{NdefRecord.createApplicationRecord(packageName)});//写入一个网址 //ndefMessage=new NdefMessage(new NdefRecord[]{NdefRecord.createUri(Uri.parse("http://www.baidu.com"))});int size=ndefMessage.toByteArray().length;    Toast.makeText(this, "要写入信息的长度"+size, Toast.LENGTH_SHORT).show();    Ndef ndef=Ndef.get(tag);        if(ndef!=null){    try {ndef.connect();if(!ndef.isWritable()){Toast.makeText(this, "NFC卡不支持写入", Toast.LENGTH_SHORT).show();return;}if(ndef.getMaxSize()<size){Toast.makeText(this, "NFC卡内存不够", Toast.LENGTH_SHORT).show();return;}ndef.writeNdefMessage(ndefMessage);Toast.makeText(this, "NFC卡写入成功", Toast.LENGTH_SHORT).show();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FormatException e) {// TODO Auto-generated catch blocke.printStackTrace();}    }else{    Toast.makeText(this, "此卡不是ndef格式", Toast.LENGTH_SHORT).show();    new AlertDialog.Builder(this).setTitle("是否格式化成ndef格式,并写入包名")    .setPositiveButton("是", new AlertDialog.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubNdefFormatable  formatable=NdefFormatable.get(tag);if(formatable==null){Toast.makeText(MainActivity.this, "此卡不能ndef格式化", Toast.LENGTH_SHORT).show();    return;}try {formatable.connect();formatable.format(ndefMessage);Toast.makeText(MainActivity. this, "NFC卡写入成功", Toast.LENGTH_SHORT).show();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FormatException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).setNegativeButton("否", null).create().show();    }}}

0 0