how to display nfc tag? - java

When I read NFC tag Read an NFC tag message only will displayed. What did I miss? Is there a way to detect NFC ID?
I followed this tutorial.
package com.example.zmynfc;
import java.util.Arrays;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mIntentFilters;
private String[][] mNFCTechLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView)findViewById(R.id.textView1);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter != null) {
mTextView.setText("Read an NFC tag");
} else {
mTextView.setText("This phone is not NFC enabled.");
}
// create an intent with tag data and deliver to this activity
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// set an intent filter for all MIME data
IntentFilter ndefIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefIntent.addDataType("*/*");
mIntentFilters = new IntentFilter[] { ndefIntent };
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}
mNFCTechLists = new String[][] { new String[] { NfcF.class.getName() } };
}
#Override
public void onNewIntent(Intent intent) {
String action = intent.getAction();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String s = action + "\n\n" + tag.toString();
// parse through all NDEF messages and their records and pick text type only
Parcelable[] data = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (data != null) {
try {
for (int i = 0; i < data.length; i++) {
NdefRecord [] recs = ((NdefMessage)data[i]).getRecords();
for (int j = 0; j < recs.length; j++) {
if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(recs[j].getType(), NdefRecord.RTD_TEXT)) {
byte[] payload = recs[j].getPayload();
String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
int langCodeLen = payload[0] & 0077;
s += ("\n\nNdefMessage[" + i + "], NdefRecord[" + j + "]:\n\"" +
new String(payload, langCodeLen + 1, payload.length - langCodeLen - 1,
textEncoding) + "\"");
}
}
}
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}
}
mTextView.setText(s);
}
#Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null)
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mNFCTechLists);
}
#Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
}

Add this in your onCreate() method:
private NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
private PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
Then write this for intercept NFC id:
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
String rfid = byteToHex(id);
}
public String byteToHex(byte[] args) {
String risultato = "";
for (int i = 0; i < args.length; i++) {
risultato += Integer.toString((args[i] & 0xff) + 0x100,16).substring(1);
}
return risultato;
}
public void enableForegroundMode() {
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter[] writeTagFilters = new IntentFilter[] {tagDetected};
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
public void disableForegroundMode() {
adapter.disableForegroundDispatch(this);
}
public void onResume() {
super .onResume();
enableForegroundMode();
}
public void onPause() {
super .onPause();
disableForegroundMode();
}

Related

How to show Hexadecimal unique ID NFC Tag have in my android NFC application?

I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.
Here is the code :
public class MainActivity extends Activity {
NfcAdapter mAdapter;
Tag mTag;
PendingIntent mPI;
IntentFilter mFilter[];
String userData,yo;
boolean writeMode;
Context context;
TextView tvNFCContent, Timer,Low;
Button start, pause, reset, lap ;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
Handler handler;
int Seconds, Minutes, MilliSeconds ;
ListView listView ;
String[] ListElements = new String[] { };
List<String> ListElementsArrayList ;
ArrayAdapter<String> adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNFCContent = (TextView) findViewById(R.id.data);
Timer = (TextView)findViewById(R.id.timer);
tvNFCContent.addTextChangedListener(watch);
handler = new Handler() ;
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPI = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilter = new IntentFilter[]{tagDetected,filter2};
mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
}
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 {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText("NFC Content: " + text);
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
}
NdefMessage[] getNdefMessage(Intent intent)
{
NdefMessage[] msgs = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(rawMsgs != null)
{
msgs = new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i] = (NdefMessage)rawMsgs[i];
}
}
return msgs;
}
#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
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
super.onNewIntent(intent);
if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();
}else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
NdefMessage[] messages = getNdefMessage(intent);
if(messages == null)
{
Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
return;
}
byte[] payload = messages[0].getRecords()[0].getPayload();
userData = new String(payload);
} else {
Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
}
}
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);
}
TextWatcher watch = new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int a, int b, int c) {
// TODO Auto-generated method stub
}
};
}
I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.
Add this code in onNewIntent()
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] uid = tag.getId(); //This is the Unique IDentifier of the card
Use the following method to get hex value
public static String getHexValue(final byte[] buffer) {
if (buffer == null || buffer.length == 0) {
return ("0x" + "[none]");
}
final StringBuffer sb = new StringBuffer();
sb.append("0x");
for (int i = 0; i < buffer.length - 1; i++) {
sb.append(String.format("%02X%s", buffer[i], ""));
}
sb.append(String.format("%02X", buffer[buffer.length - 1]));
return sb.toString();
}
Finally I can make it. Thanks for everyone that helped me. Here is the full code I share it with you.
package com.nfcreadfull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.List;
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.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
NfcAdapter mAdapter;
Tag mTag;
PendingIntent mPI;
IntentFilter mFilter[];
String userData,yo;
boolean writeMode;
Context context;
TextView tvNFCContent, Timer,Low, Uid;
Button start, pause, reset, lap ;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
int Seconds, Minutes, MilliSeconds ;
ListView listView ;
String[] ListElements = new String[] { };
List<String> ListElementsArrayList ;
ArrayAdapter<String> adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvNFCContent = (TextView) findViewById(R.id.data);
Timer = (TextView)findViewById(R.id.timer);
Uid = (TextView)findViewById(R.id.uid);
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPI = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilter = new IntentFilter[]{tagDetected,filter2};
mAdapter = NfcAdapter.getDefaultAdapter(this);
if (mAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
}
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 {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText("NFC Content: " + text);
}
NdefMessage[] getNdefMessage(Intent intent)
{
NdefMessage[] msgs = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if(rawMsgs != null)
{
msgs = new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i] = (NdefMessage)rawMsgs[i];
}
}
return msgs;
}
#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
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
Uid.setText(ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
super.onNewIntent(intent);
if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();
}else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
{
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefMessage[] messages = getNdefMessage(intent);
if(messages == null)
{
Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
return;
}
byte[] payload = messages[0].getRecords()[0].getPayload();
userData = new String(payload);
}else
{
Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
}
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
// While with ForegroundDispatch the NDEF message has already been read
// And passed to us in the intent and thus the time the App spends "read" the NFC card is Zero
// We want to time time the read, so now we have been notified that a NDEF card is in range
// Try and read from it
// Get the Tag from the intent
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
long startTime = 0;
long endTime = 0;
try {
// Create an NDEF tag object
Ndef ndefTag = Ndef.get(tag);
// This is the I/O operation to read the card and format the result to an NDEF message
// Nothing is done with the result to not add any time to it, as we are timing this
startTime = System.currentTimeMillis();
ndefTag.connect();
ndefTag.getNdefMessage();
endTime = System.currentTimeMillis();
ndefTag.close();
} catch (Exception e) {
Log.e("NFC", e.toString());
}
MillisecondTime = endTime - startTime;
UpdateTime = MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
Timer.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + "."
+ String.format("%03d", MilliSeconds));
//Log.v("NFC", "Time to read in milliseconds is: " + (endTime - startTime));
//Timer.setText("00:00:0.0"+(endTime - startTime));
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefDetected.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {}
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(mAdapter!= null)
mAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
private String getHex(byte[] bytes) {
if (bytes == null) {
return null;
}
char[] hexChars = new char[bytes.length * 2];
final char[] hexArray = "0123456789abcdef".toCharArray();
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private long getDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private String ByteArrayToHexString(byte [] inarray) {
Log.d("ByteArrayToHexString", inarray.toString());
int i, j, in;
String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String out= "";
for(j = 0 ; j < inarray.length ; ++j)
{
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));
return out;
}
}

Why am I getting a reversed NFC Tag ID (Hex)?

I want my app to scan an NFC tag and get its ID and tag type. But somehow my code reads a reversed tag ID.
For instance my app reads the following tag ID (hex): 80 65 69 e2 f5 fe 04
while 4 other similar apps from Google Play Store read the following ID: 4 fe f5 e2 69 65 80 (where the first zero is also missing)
I want my app to read the tag ID without reverting the bytes, how can I achieve that? Here is my complete code:
package com.asetnfc;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import static android.content.ContentValues.TAG;
//public class MainActivity extends AppCompatActivity {
public class InfoNFC extends Activity {
private TextView mTextView; //ECP 2017-01-16
// list of NFC technologies detected:
private final String[][] techList = new String[][] {
new String[] {
NfcA.class.getName(),
NfcB.class.getName(),
NfcF.class.getName(),
NfcV.class.getName(),
IsoDep.class.getName(),
MifareClassic.class.getName(),
MifareUltralight.class.getName(), Ndef.class.getName()
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.infonfc);
mTextView = (TextView) findViewById(R.id.infonfctype);
mTextView.setText("Data Tampil Disini");
}
#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
protected void onResume() {
super.onResume();
Log.d("onResume", "1");
//mTextView.setText("onResume:");
// creating pending intent:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// creating intent receiver for NFC events:
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
// enabling foreground dispatch for getting intent from NFC event:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
}
#Override
protected void onPause() {
super.onPause();
Log.d("onPause", "1");
// disabling foreground dispatch:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onNewIntent(Intent intent) {
Log.d("onNewIntent", "1");
if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
Log.d("onNewIntent", "2");
mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
//if(getIntent().hasExtra(NfcAdapter.EXTRA_TAG)){
Parcelable tagN = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tagN != null) {
Log.d(TAG, "Parcelable OK");
NdefMessage[] msgs;
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
byte[] payload = dumpTagData(tagN).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
msgs = new NdefMessage[] { msg };
//Log.d(TAG, msgs[0].toString());
}
else {
Log.d(TAG, "Parcelable NULL");
}
Parcelable[] messages1 = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages1 != null) {
Log.d(TAG, "Found " + messages1.length + " NDEF messages");
}
else {
Log.d(TAG, "Not EXTRA_NDEF_MESSAGES");
}
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
if(ndef != null) {
Log.d("onNewIntent:", "NfcAdapter.EXTRA_TAG");
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages != null) {
Log.d(TAG, "Found " + messages.length + " NDEF messages");
}
}
else {
Log.d(TAG, "Write to an unformatted tag not implemented");
}
//mTextView.setText( "NFC Tag\n" + ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_TAG)));
}
}
private String dumpTagData(Parcelable p) {
StringBuilder sb = new StringBuilder();
Tag tag = (Tag) p;
byte[] id = tag.getId();
sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech : tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech : tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
MifareClassic mifareTag = MifareClassic.get(tag);
String type = "Unknown";
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
Log.d("Datos: ", sb.toString());
mTextView.setText('\n' + sb.toString());
return sb.toString();
}
private String getHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private long getDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private String ByteArrayToHexString(byte [] inarray) {
Log.d("ByteArrayToHexString", inarray.toString());
int i, j, in;
String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String out= "";
for(j = 0 ; j < inarray.length ; ++j)
{
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
//CE7AEED4
//EE7BEED4
Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));
return out;
}
}
In your function getHex() you are starting from last byte and then decrementing the i counter.
try to use this function:
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHexString(byte[] bytes) {
if (bytes == null) {
return null;
}
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}

Android TTS how to display speaking word in textview

How can i display tts output as text view when word speaking.
Actually i want to display tts output words in textview. I have 1 edittext in which i enter some data and then when click on play button it performs speech but i also want to display speaking words in text view how can i do this any one can help me. i also think about convert text into array form and then pass but, i don't think it useful any other solution ?
Code which i do currently.
For Example: If TTS is speaking this string: How are you! and when it reaches 'how', how can I display 'how' in text view only single word.
Initializations();
textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(MainActivity.this, "Sorry ! Language data missing", Toast.LENGTH_SHORT).show();
} else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "Sorry ! Language not supported", Toast.LENGTH_SHORT).show();
} else {
speek.setEnabled(true);
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(MainActivity.this, "Sorry ! Text to speech can't be initialized", Toast.LENGTH_SHORT).show();
speek.setEnabled(false);
}
}
});
speek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SpeekOut();
}
});
private void SpeekOut() {
String text = etTextToSpeech.getText().toString();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Try this to read
add this in any button click.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
Intent i = new Intent(MainService.ACTION);
if (isServiceRunning()) {
stopService(i);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
} else {
startService(i);
runAsForeground();
}
try { startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show();
}
//runAsForeground function here
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Night Mode")
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
To display in the textview
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
//MainService
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
public class MainService extends Service {
public static final String ACTION = "com.thul.CallRecorder.CALL_RECORD";
public static final String STATE = "STATE";
public static final String START = "START";
public static final String STORAGE = "STORAGE";
public static final String INCOMING = "INCOMING";
public static final String OUTGOING = "OUTGOING";
public static final String BEGIN = "BEGIN";
public static final String END = "END";
protected static final String TAG = MainService.class.getName();
protected static final boolean DEBUG = false;
private static final String AMR_DIR = "/callrec/";
private static final String IDLE = "";
private static final String INCOMING_CALL_SUFFIX = "_i";
private static final String OUTGOING_CALL_SUFFIX = "_o";
private Context cntx;
private volatile String fileNamePrefix = IDLE;
private volatile MediaRecorder recorder;
private volatile PowerManager.WakeLock wakeLock;
private volatile boolean isMounted = false;
private volatile boolean isInRecording = false;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.cntx = getApplicationContext();
this.prepareAmrDir();
log("service create");
}
#Override
public void onDestroy() {
log("service destory");
this.stopRecording();
this.cntx = null;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null == intent || !ACTION.equals(intent.getAction())) {
return super.onStartCommand(intent, flags, startId);
}
String state = intent.getStringExtra(STATE);
String phoneNo = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
log("state: " + state + " phoneNo: " + phoneNo);
if (OUTGOING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ OUTGOING_CALL_SUFFIX;
} else if (INCOMING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ INCOMING_CALL_SUFFIX;
} else if (BEGIN.equals(state)) {
startRecording();
} else if (END.equals(state)) {
stopRecording();
} else if (STORAGE.equals(state)) {
String mountState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(mountState)) {
prepareAmrDir();
} else {
isMounted = false;
}
if (!isInRecording) {
stopSelf();
}
}
return START_STICKY;
}
public Context getContext() {
return cntx;
}
private void stopRecording() {
if (isInRecording) {
isInRecording = false;
recorder.stop();
recorder.release();
recorder = null;
releaseWakeLock();
stopSelf();
log("call recording stopped");
}
}
private String getDateTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
Date now = new Date();
return sdf.format(now);
}
private String getMonthString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date now = new Date();
return sdf.format(now);
}
private String getDateString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
return sdf.format(now);
}
private String getTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date now = new Date();
return sdf.format(now);
}
private void startRecording() {
if (!isMounted)
return;
stopRecording();
try {
File amr = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ getDateTimeString()
+ "_"
+ fileNamePrefix + ".amr");
log("Prepare recording in " + amr.getAbsolutePath());
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(amr.getAbsolutePath());
recorder.prepare();
recorder.start();
isInRecording = true;
acquireWakeLock();
log("Recording in " + amr.getAbsolutePath());
} catch (Exception e) {
Log.w(TAG, e);
}
}
private void prepareAmrDir() {
isMounted = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isMounted)
return;
File amrRoot = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + AMR_DIR);
if (!amrRoot.isDirectory())
amrRoot.mkdir();
}
private String getContactName(Context cntx, String phoneNo) {
if (null == phoneNo)
return "";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
ContentResolver cr = cntx.getContentResolver();
Cursor c = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
null, null, null);
if (null == c) {
log("getContactName: The cursor was null when query phoneNo = "
+ phoneNo);
return phoneNo;
}
try {
if (c.moveToFirst()) {
String name = c.getString(0);
name = name.replaceAll("(\\||\\\\|\\?|\\*|<|:|\"|>)", "");
log("getContactName: phoneNo: " + phoneNo + " name: " + name);
return name;
} else {
log("getContactName: Contact name of phoneNo = " + phoneNo
+ " was not found.");
return phoneNo;
}
} finally {
c.close();
}
}
private void log(String info) {
if (DEBUG && isMounted) {
File log = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ "log_"
+ getMonthString()
+ ".txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(log,
true));
try {
synchronized (out) {
out.write(getDateString()+getTimeString());
out.write(" ");
out.write(info);
out.newLine();
}
} finally {
out.close();
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
private void acquireWakeLock() {
if (wakeLock == null) {
log("Acquiring wake lock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
log("Wake lock released");
}
}
}
//isServiceRunning
private boolean isServiceRunning() {
ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().equals(
MainService.class.getName())) {
return true;
}
}
return false;
}

Blocking any other application via Service

I'm creating a business application and must block any other application that the user tries to open. I am creating a service to it, but it's not working.
When run, it does not see the other applications when opened by the user.
I read some other posts here, but I could not solve.
Below is my service.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
startService(new Intent(this, clsServico.class));
}
my class:
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class clsServico extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // em segundos
private static final String TAG = clsServico.class.getSimpleName();
private static final String APS_BG = "APS_BG";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
ctx = this;
// checa periodicamente se tem algum outro app na tela
t = new Thread(new Runnable() {
#Override
public void run() {
do {
//checkAPS();
try {
if(Build.VERSION.SDK_INT >= 21)
listTasks();
else
listTasks_SDK21();
} catch (PackageManager.NameNotFoundException e) {
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
public void listTasks() throws PackageManager.NameNotFoundException {
if(Build.VERSION.SDK_INT >= 21) {
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
String packagename;
String label;
for (ActivityManager.AppTask task : tasks) {
packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
//Log.i(TAG, packagename + ":" + label);
}
}
}
public void listTasks_SDK21() throws PackageManager.NameNotFoundException {
ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = mgr.getRecentTasks(20, 0);
String packagename;
String label;
for(ActivityManager.RecentTaskInfo task: tasks){
packagename = task.baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
Log.i(TAG,packagename + ":" + label);
}
}
private void checkAPS() {
/*
if(apenasAPSAtivado(ctx)) {
if(isInBackground()) {
restoreApp(); // tras p frente
}
}
*/
PackageManager packageManager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ResolveInfo> appList = packageManager.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(packageManager));
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
ApplicationInfo a = p.applicationInfo;
// skip system apps if they shall not be included
if((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
continue;
}
//Log.i("packageName","" + p.packageName);
}
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo run = RunningTask.get(0);
Log.i("topActivity", run.topActivity.getClassName());
Intent ints = new Intent(Intent.ACTION_MAIN, null);
ints.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> intentlist = packageManager.queryIntentActivities(ints, PackageManager.PERMISSION_GRANTED);
List<ActivityManager.RunningTaskInfo> processes = mActivityManager.getRunningTasks(Integer.MAX_VALUE);
String pName = "";
if (processes != null)
{
for (int i = 0; i < processes.size(); i++) {
String packageName = processes.get(i).topActivity.getPackageName();
ActivityManager.RunningTaskInfo temp = processes.get(i);
try
{
pName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
//Log.i("RunningTaskInfo",pName + " : " + temp.id);
/*
if (savedapp.equals(pName)) {
// finish(pm.);
int code = intentlist.get(i).activityInfo.hashCode();
finishActivity(code);
mActivityManager.killBackgroundProcesses(packageName);
mActivityManager.restartPackage(packageName);
android.os.Process.killProcess(temp.id);
finishActivity(temp.id);
}
*/
}
}
List<ActivityManager.RunningTaskInfo> rt = mActivityManager.getRunningTasks(1000);
for(int i = 0; i < rt.size(); i++){
ActivityManager.RunningTaskInfo ar = rt.get(i);
String activityOnTop=ar.topActivity.getClassName();
//Log.i("rt", activityOnTop);
}
//ActivityManager.RunningTaskInfo ar = rt.get(0);
//String activityOnTop=ar.topActivity.getClassName();
//Log.i("activityOnTop", activityOnTop);
//ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = mActivityManager.getRunningAppProcesses();
for(int i = 0; i < pids.size(); i++)
{
ActivityManager.RunningAppProcessInfo p = pids.get(i);
if(!p.processName.equalsIgnoreCase("nog.aps3")){
android.os.Process.killProcess(p.pid);
try {
android.os.Process.killProcess(p.pid);
android.os.Process.sendSignal(p.pid, android.os.Process.SIGNAL_KILL);
mActivityManager.killBackgroundProcesses(p.processName);
} catch (Exception e) {
e.printStackTrace();
//Log.i("try", e.toString());
}
}
//Log.i("info.processName", p.processName);
//isInBackground();
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
//Log.i("getPackageName", ctx.getApplicationContext().getPackageName() +" =? "+ componentInfo.getPackageName());
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
//restore other class
}
public boolean apenasAPSAtivado(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(APS_BG, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Can anyone help me with this, pls?

Updating the UI upon receiving an android push notification

I have a query regarding android push notification and i had asked it in another stackoverflow post and i did not get much help out of it [Query regarding Android push notifications. So i am posting it again, and it is as follows:
I have an android app that receives push notifications from Google push notification service. When i tap on the received notification, it opens an UI which displays this message, it is a list view. Now, when the user receives the push notification, and assuming that this screen is open, the UI should be refreshed automatically, such that it displays the latest notification. Could anybody let me know how i can solve this?
Below is my code that i have implemented:
Java code to receive the notification:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import com.example.foodu.R;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCM ::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "53340195486";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
#Override
protected void onMessage(Context context, Intent data) {
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, com.example.foodu.Notification.class);
// Pass data to the new activity
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setWhen(System.currentTimeMillis())
.setContentTitle("Deals")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}
#Override
protected void onUnregistered(Context arg0, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
}
The code for the corresponding activity that would be launched when the user taps on the notification:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import com.example.foodu.R;
import com.example.foodu.R.drawable;
import com.example.foodu.R.id;
import com.example.foodu.R.layout;
import com.example.foodu.R.menu;
import com.google.android.gcm.GCMRegistrar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Notification extends ActionBarActivity {
LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>();
ListView listView = null;
NotificationListAdapter adaptor;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
listView = (ListView) findViewById(R.id.listView1);
// Retrive the data from GCMIntentService.java
Intent i = getIntent();
String message = i.getStringExtra("message");
//getDataForDisplay();
if(message!=null)
{
parseData(message);
}else{
getDataToDisplay();
}
adaptor = new NotificationListAdapter(getApplicationContext(), notificationList);
listView.setAdapter(adaptor);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText("No Events Yet!");
listView.setEmptyView(emptyText);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
onListitemSelect(position);
view.setSelected(true);
return true;
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
adaptor.notifyDataSetChanged();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
void writeToFile(){
FileOutputStream fos;
try {
fos = openFileOutput("varun", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(notificationList);
oos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void readFromFile(){
try{
FileInputStream fis = openFileInput("varun");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject();
ois.close();
for (int i = 0; i < local.size(); i++) {
notificationList.add(local.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getDataToDisplay() {
// TODO Auto-generated method stub
readFromFile();
}
private void parseData(String message) {
try {
int len = 0;
String[] stringArr = new String[100];
StringTokenizer st = new StringTokenizer(message, ".");
len = st.countTokens();
for (int i = 0; i < len; i++) {
if (st.hasMoreTokens()) {
stringArr[i] = st.nextToken();
}
}
NotificationData data = new NotificationData();
data.title = stringArr[0];
data.venue = stringArr[1];
data.date = stringArr[2];
data.time = stringArr[3];
notificationList.add(data);
readFromFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDateToDisplay() {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
writeToFile();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notificationmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_register){
registerDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
private void registerDevice() {
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar
.register(Notification.this, GCMIntentService.SENDER_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.notificationcontext, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_calender:
addToCalender();
mode.finish();
return true;
case R.id.menu_delete:
//deleteData();
showAlertBox();
return false;
case R.id.menu_share:
shareDate();
mode.finish();
return true;
case R.id.menu_copy:
copyToClip();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
adaptor.removeSelection();
}
};
void onListitemSelect(int position) {
adaptor.toggleSelection(position);
boolean hasCheckedItems = adaptor.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null) {
mActionMode = startActionMode((Callback) mActionModeCallback);
} else if (!hasCheckedItems && mActionMode != null) {
mActionMode.finish();
}
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount()));
}
protected void showAlertBox() {
// TODO Auto-generated method stub
AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this);
builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?");
builder1.setCancelable(true);
builder1.setIcon(R.drawable.alert);
builder1.setTitle("Caution");
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteData();
mActionMode.finish();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
protected void copyToClip() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Notification App", shareText);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Data copied to ClipBoard",
Toast.LENGTH_LONG).show();
}
protected void shareDate() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
String share = shareText.toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, share);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
protected void deleteData() {
int count = 0;
int startPoint = adaptor.getSelectedIds().keyAt(0);
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
adaptor.remove(notificationList.get(startPoint));
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message+" deleted", Toast.LENGTH_LONG)
.show();
}
private void addToCalender() {
try {
int count = 0;
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
ContentResolver cr = getApplicationContext()
.getContentResolver();
ContentValues values = new ContentValues();
String myDate = data.date + " " + data.time;
String timeArr[] = data.time.split("to");
SimpleDateFormat sfd = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault());
long time = sfd.parse(myDate).getTime();
values.put(CalendarContract.Events.DTSTART, time);
if (timeArr.length > 0) {
String endTime = timeArr[1];
SimpleDateFormat timeFormat = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy hh a", Locale.getDefault());
long endtime = timeFormat.parse(data.date + " " + endTime)
.getTime();
values.put(CalendarContract.Events.DTEND, endtime);
}
values.put(CalendarContract.Events.TITLE, data.title);
values.put(CalendarContract.Events.DESCRIPTION, data.venue);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE,
timeZone.getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr
.insert(CalendarContract.Events.CONTENT_URI, values);
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message + " added to Calender", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use LocalBroadcastManager
Check following code / steps
1) Add in your activity (UI refresh Activity)
private BroadcastReceiver mMyBroadcastReceiver;
Then ,
2) In onResume
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
Toast.makeText(getApplicationContext(), "Receiver", 2000).show();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action"));
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}}
// and your other code
3) Then unregister in onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4) Finally add in your GCM reciver class.
first check your activity is Visible or not using static variable
if visible add
Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec);
else
use Notification Manager for notification.
I think this is easy and best way to refresh your listview UI / call Fetching method.

Categories