how to mimic restarting an application without actually exiting it - java

by "restarting" the application, what I am essentially attempting to do is reset all the instance variables, fields, activities, services, and just everything the application to how it was when it was first opened. The only caveat is that I don't want to actually exit out of the app itself. Is there any way I would be accomplish this?

There's really no quick and easy solution to reset everything.
The main reason is because there's no way of knowing everything you want to reset. For example, there's a simple way to reset an Activity by relaunching the Activity and clearing the old one... however, this only resets the Activity minus the static variables. It also doesn't touch Services, Singletons, and other static values you've changed.
Only proper and reliable solution is to create a resetAll() method yourself. Have it send the reset commands to every active Service, change back default values for current Activity, null the Singletons, and etc.

What I did before on android (iOS doesn't allow to restart an app) is use a PendingIntent with a code for clearing the cache of the app. It still exits the app but it restarts it like it's from a fresh install.
cleanCache();
PackageManager pm = context.getPackageManager();
if(pm != null){
Intent activity = pm.getLaunchIntentForPackage(getBaseContext().getPackageName());
if(activity != null){
activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int pendingIntentId = 223344;
PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, activity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 5, pendingIntent);
System.exit(0);
}else{
Log.d(TAG, "was not able to restart, activity null");
}
}else{
Log.d(TAG, "was not able to restart, pm null");
}
public class ExitActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exit);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
Then below are the code for cleanCache().
private void cleanCache() {
clearApplicationData();
Intent intent = new Intent(context, ExitActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
public void clearApplicationData(){
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
webMain.clearCache(true);
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir){
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
Then below is the code for ExitActivity.
public class ExitActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exit);
android.os.Process.killProcess(android.os.Process.myPid());
}
}

Related

Should I tap NFC tag every time I want to write in it?

I'm an android developer
I have an idea to develop an application that writes on NFC tags data. (Only writing)
I have an Edit Text and a button and when I click on the button I write on the NFC the data written in the field
I searched a lot and tried several codes
The only problem is my NFC tags sticks in the back of the phone and the code i'm using tells me I have to tap/tag the NFC tag to write in it
Is there another way to detect the NFC tag sticked on the back of the phone when clicking the button?
I have two activities main activity that will call methods from my NFCManager
I will share below the NFCManager class
NFCManager class:
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.Ndef;
import android.nfc.tech.NdefFormatable;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
public class NFCManager {
private Activity activity;
private NfcAdapter nfcAdpt;
public NFCManager(Activity activity) {
this.activity = activity;
}
public void verifyNFC() throws NFCNotSupported, NFCNotEnabled {
nfcAdpt = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdpt == null)
throw new NFCNotSupported();
if (!nfcAdpt.isEnabled())
throw new NFCNotEnabled();
}
public void enableDispatch() {
Intent nfcIntent = new Intent(activity, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[] {};
String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
nfcAdpt.enableForegroundDispatch(activity, pendingIntent, intentFiltersArray, techList);
}
public void disableDispatch() {
nfcAdpt.disableForegroundDispatch(activity);
}
public static class NFCNotSupported extends Exception {
public NFCNotSupported() {
super();
}
}
public static class NFCNotEnabled extends Exception {
public NFCNotEnabled() {
super();
}
}
public void writeTag(Tag tag, NdefMessage message) {
if (tag != null) {
try {
Ndef ndefTag = Ndef.get(tag);
if (ndefTag == null) {
// Let's try to format the Tag in NDEF
NdefFormatable nForm = NdefFormatable.get(tag);
if (nForm != null) {
nForm.connect();
nForm.format(message);
nForm.close();
}
}
else {
ndefTag.connect();
ndefTag.writeNdefMessage(message);
ndefTag.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public NdefMessage createUriMessage(String content, String type) {
NdefRecord record = NdefRecord.createUri(type + content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
}
public NdefMessage createTextMessage(String content) {
try {
// Get UTF-8 byte
byte[] lang = Locale.getDefault().getLanguage().getBytes("UTF-8");
byte[] text = content.getBytes("UTF-8"); // Content in UTF-8
int langSize = lang.length;
int textLength = text.length;
ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + langSize + textLength);
payload.write((byte) (langSize & 0x1F));
payload.write(lang, 0, langSize);
payload.write(text, 0, textLength);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
return new NdefMessage(new NdefRecord[]{record});
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public NdefMessage createExternalMessage(String content) {
NdefRecord externalRecord = NdefRecord.createExternal("com.survivingwithandroid", "data", content.getBytes());
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { externalRecord });
return ndefMessage;
}
}
Methods from my MainActivity:
#Override
protected void onResume() {
super.onResume();
try {
nfcMger.verifyNFC();
//nfcMger.enableDispatch();
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[] {};
String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
NfcAdapter nfcAdpt = NfcAdapter.getDefaultAdapter(this);
nfcAdpt.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
}
catch(NFCManager.NFCNotSupported nfcnsup) {
Snackbar.make(v, "NFC not supported", Snackbar.LENGTH_LONG).show();
}
catch(NFCManager.NFCNotEnabled nfcnEn) {
Snackbar.make(v, "NFC Not enabled", Snackbar.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
nfcMger.disableDispatch();
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("Nfc", "New intent");
// It is the time to write the tag
currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (message != null) {
nfcMger.writeTag(currentTag, message);
dialog.dismiss();
Snackbar.make(v, "Tag written", Snackbar.LENGTH_LONG).show();
} else {
// Handle intent
}
}
There is another and much better way to get notified that a Tag comes in to range especially if you are writing to a Tag, this is called enableReaderMode but you use case is strange.
I'm not sure why you would want an NFC tag stuck on the back of a phone because then it would act like very slow and small sized permanent storage when a file on the phones memory would be far better.
Remember once the Tag comes in to range you get notified via enableForegroundDispatch or enableReaderMode that a Tag has come in to range and get given a Tag object. As long as that Tag does not go out of range and you have stored the Tag object in the global scope of the activity then you can write to it as many times you like and for as long as you like.
Therefore it should be possible if complicated to do what you wand and write (or read) when even the user click a button.
I've not tested whether a Tag object is usable after your App is put in to the background and brought to the foreground again, but I think it is unlikely because a background App might be closed and closure would definitely invalid the Tag object.
But there are 2 problems with your code.
Really calling connect and write to your Tag should never be done on the UI thread as it is IO blocking and could be cancelled which would cause the Tag to be taken out of range and brought back in to range again. Luckily if you use enableReaderMode then you get notified in a separate thread.
You should only call close on the Tag when you no longer want to write to it, at the moment you are calling close after you have written once to it.
So the following will probably work for you but with the limitation that the Tag has to come in to range the first time after the App has started.
Use enableReaderMode to get notified that the Tag initially comes in to range, Store the Tag object in the global Activity scope and connect to it once in the enableReaderMode callback thread.
The from the UI when the button is press, start a new Thread to write to the tag.
Never call close on the Tag Object.
Note I've not tested this as it is a very strange use case.

Sending intents from a worker to an activity in a separate app

I have an app that writes to its local storage depending on user actions; said contents need to
be forwarded to another app.
My approach:
create a worker thread with a file observer pointed to local storage
start worker from the apps main activity
worker thread creates and sends intents with updated contents to separate app
I'm not sure (maybe need to open a separate question), but everything created in an activity gets destroyed when the activity is stopped, right? meaning that adding workers, file observers have the same life span as the activity they're defined in, right?
Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String FILE_OBSERVER_WORK_NAME = "file_observer_work";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Creating file observer worker");
WorkManager workManager = WorkManager.getInstance(getApplication());
WorkContinuation continuation = workManager
.beginUniqueWork(FILE_OBSERVER_WORK_NAME,
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequest.from(APIWorker.class));
Log.i(TAG, "Starting worker");
continuation.enqueue();
final Button button = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, "Button clicked!");
String stuffToWriteToFile = getStuff();
String cwd = getApplicationInfo().dataDir;
String stuffFilePath= cwd + File.separator + "stuff.json";
PrintWriter stuffFile= null;
try {
stuffFile = new PrintWriter(stuffFilePath, "UTF-8");
stuffFile.println(stuffToWriteToFile);
stuffFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onResume(){
super.onResume();
// start worker here?
}
#Override
public void onStart() {
super.onStart();
// start worker here?
}
}
APIWorker.java:
public class APIWorker extends Worker {
public APIWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
private static final String TAG = APIWorker.class.getSimpleName();
#NonNull
#Override
public Result doWork() {
Context applicationContext = getApplicationContext();
Log.d(TAG, "Observing stuff file");
FileObserver fileObserver = new FileObserver(cwd) {
#Override
public void onEvent(int event, #Nullable String path) {
if(event == FileObserver.CREATE ||
event == FileObserver.MODIFY) {
String cwd = applicationContext.getApplicationInfo().dataDir;
String stuffFilePath = cwd + File.separator + "stuff.json";
String fileContents;
File observedFile = new File(stuffFilePath);
long length = observedFile.length();
if (length < 1 || length > Integer.MAX_VALUE) {
fileContents = "";
Log.w(TAG, "Empty file: " + observedFile);
} else {
try (FileReader in = new FileReader(observedFile)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + observedFile +
". Read chars " + numRead + " of " + length);
}
fileContents = new String(content, 0, numRead);
Log.d(TAG, "Sending intent ");
String packageName = "com.cam.differentapp";
Intent sendIntent = applicationContext.getPackageManager().
getLaunchIntentForPackage(packageName);
if (sendIntent == null) {
// Bring user to the market or let them choose an app?
sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("market://details?id=" + packageName));
}
// sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, fileContents);
sendIntent.setType("application/json");
applicationContext.startActivity(sendIntent);
Log.d(TAG, "Intent sent ");
}
catch (Exception ex) {
Log.e(TAG, "Failed to read file " + path, ex);
fileContents = "";
}
}
}
}
};
fileObserver.startWatching();
return null;
}
}
Looking at the docs:
https://developer.android.com/guide/components/activities/background-starts
there are restrictions as to when activities can be started from the background but also exceptions, namely:
The app has a visible window, such as an activity in the foreground.
meaning (I think?) that as long as the user interacts with the app (MainActivity) the background worker should run, correct? It's stopped if the activity is paused/destroyed, right?
Usually you would use a Service if you have background processing to do that doesn't need user interaction (display or user input). If your app is in the foreground then your Service can launch other activities using startActivity().
Your architecture seems very strange to me. You are using a Worker, which has a maximum 10 minute lifetime. You are starting the Worker which then creates a FileObserver to detect creation/modification of files. It then reads the file and starts another Activity. This is a very complicated and roundabout way of doing things. I have doubts that you can get this working reliably.
Your Activity is writing the data to the file system. It could just call a method (on a background thread) after it has written the file that then forwards the data to another Activity. This would be much more straightforward and has a lot less moving parts.
I don't know exactly how the lifecycle of the Activity effects the Workers. I would assume that they are not directly linked to the Activity and therefore would not stop when the Activity is paused or destroyed.
I also notice that you are writing to a file on the main (UI) thread (in your OnClickListener). This is not OK and you should do file I/O in a background thread, because file I/O can block and you don't want to block the main (UI) thread.

Why does foreground service stop working when device go into sleep mode

I want to create an app that is constantly checking for location change and put the current location in the firebase (e.g. an app for runners).
Unfortunately the foregroundservice is being stopped or paused every time the device go into sleep mode.
For starters I wanted to create a foreground service that is continuously writing information to the base (that would be a time stamp or a simple string) every second.
After some time it just stops writing to firebase without calling stopself().
The service is working fine on the emulator (even if put to sleep), but stops when tested on a real device – in my case Huawei, Android 8.1.0.
What should I do to force service to run in every state of the device?
My MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "start");
startForegroundService(intent);
}
else {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "start");
startService(intent);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "stop");
startForegroundService(intent);
}
else {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "stop");
startService(intent);
}
}
}
MyService:
public class MyService extends Service {
int i =0;
private String CHANNEL_ID = "2345";
#Override
public void onCreate() {
super.onCreate();
}
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1000, createNotification());
String action = intent.getExtras().getString("action");
switch (action){
case "start":
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
myfunction();
handler.postDelayed(this, 1000);
}
};
break;
case "stop":
stopfunction();
break;
}
handler.postDelayed(runnable, 1000);
return START_NOT_STICKY;
}
private void stopfunction() {
stopSelf();
}
private void myfunction() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("locations");
myRef.child("location").setValue(i);
i++;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#RequiresApi(Build.VERSION_CODES.O)
private void createChannel(){
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.infoTxt),
NotificationManager.IMPORTANCE_HIGH);
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(channel);
}
private Notification createNotification(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
createChannel();
}
Intent notificationItent = new Intent(this, MainActivity.class);
notificationItent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, notificationItent, 0);
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setColor(ContextCompat.getColor(this, android.R.color.background_dark))
.setContentIntent(intent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setContentTitle("GPS Location")
.build();
}
}
I've tried everything: service, foreground service, broadcast receiver, jobSheduler, WorkerManager – nothing helped. Then I found it’s a new HUAWEI feature called “power-intensive app monitor “. It kills every app that runs in the background for a long time unless user gives special permissions to it.
The path to do this:
Settings -> Security & privacy -> Location services -> recent location requests: YOUR APP NAME -> Battery -> uncheck Power-intensive prompt, App launch: Manage manually: check all three positions: Auto-launch, secondary launch, run in background.
I don’t know is there a way to do this programmatically. I think the best way is to create a sort of help activity and explain the user what to do if application won’t work.
Foreground services generally should be used for task which require user attention such as visual processes.
use Background service instead

EventListener for Power Button press in a Service

I want to listen the power key event in the service.
How can in do that ?
Currently I am working with an app, where I need to listen the power button for some events, from a service which is running in a background, even when the app is killed or stopped.
Somehow I can manage to get it.
But when I kill/stop the app, the service is getting stopped.
How can i overcome this ?
Currently the code i am using this :
Service Class:
public class SampleService extends Service
{
SettingContentObserver mSettingsContentObserver;
AudioManager mAudioManager;
private ComponentName mRemoteControlResponder;
private Intent intent;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Toast.makeText(getApplicationContext(), "On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Off", Toast.LENGTH_SHORT).show();
}
}
public void onCreate()
{
mSettingsContentObserver = new SettingContentObserver(this,new Handler());
getApplicationContext().getContentResolver().registerContentObserver
(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver );
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mRemoteControlResponder = new ComponentName(getPackageName(),
StartAtBootServiceReceiver.class.getName());
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new StartAtBootServiceReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onDestroy()
{
getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);
}
}
BroadcastReceiver Class:
public class StartAtBootServiceReceiver extends BroadcastReceiver
{
static boolean wasScreenOn;
private boolean screenOff;
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
wasScreenOn = false;
Toast.makeText(context, "Power Off", Toast.LENGTH_SHORT).show();
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
wasScreenOn = true;
}
Intent i = new Intent(context, SampleService.class);
i.putExtra("screen_state", screenOff);
i.setAction("com.example.antitheft.SampleService");
context.startService(i);
//
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i1 = new Intent();
i1.setAction("com.example.sampleonkeylistener.MainActivity");
context.startService(i1);
}
}
}
given above is the sample code and i have created AndroidManifest.xml files also with user's permission but i cannot get the app continue service if it is killed or stopped.
Thanks in Advance.
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, SampleService.class));
}
This is one way to ensure that service will never stop even user want to destroy it.
This is one Just ONE of ways to achieve what you are trying to achieve.
Secondly, you can try and run service in "foreground" by using startForeground().
Also, make sure that in you return "START_STICKY" (which you are doing in the sample code that you shared and I trust that you are also doing in App's code too :) ) in Services's onStartCommand().
This will ensure that If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service.
And you may find some additional pointers/hints to make sure your service is not stopped at below link.
How can we prevent a Service from being killed by OS?
Just pick and choose the approach that best suits YOUR Need/implementation.

"New Tag Collected" instead of reading tags of application - NFC android

I have a class, which creates conncection to NFC and two activites. Both of them creates an object of that class so they can connect to NFC.
Earlier it worked somehow but now I've got problem - my application doesn't do anything onNewIntent, even on the first activity. Instead of it, I can see "New tag collected" from build-in app called "Tags" (Nexus S).
What should I do?
class:
public NFCForegroundUtil(Activity activity)
{
super();
this.activity = activity;
mAdapter = NfcAdapter.getDefaultAdapter(activity
.getApplicationContext());
mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(
activity, activity.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndef2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter ndef3 = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try
{
ndef2.addDataType("*/*");
}
catch (MalformedMimeTypeException e)
{
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] {ndef, ndef2, ndef3 };
mTechLists = new String[][] { new String[] {
// android.nfc.tech.NfcV.class.getName(),
android.nfc.tech.NfcA.class.getName(),
android.nfc.tech.IsoDep.class.getName() } };
mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
}
activity 1:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nfcForegroundUtil = new NFCForegroundUtil(this);
}
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
Intent i = new Intent(this, NfcDisplayLabelActivity2.class);
startActivity(i);
}
Go to settings -> Apps -> All -> Tags(in my case) -> disable
I had a similar problem when trying to open my app from an NFC tag. I had registered an intentfilter in my AndroidManifest.xml for the scheme "magicnfc" and yet it opened the Android OS Tags app instead of mine.
I discovered that the NFC intent (TECH_DISCOVERED in my case) had higher priority than a generic scheme-based intent filter. Because the Tags app registered TECH_DISCOVERED, it was getting opened instead of mine.
Luckily, apps can register for NDEF_DISCOVERED (a higher priority filter) and get opened instead of the Tags app.
That made my app open when I tapped the tag.
More info is here:
http://developer.android.com/guide/topics/connectivity/nfc/nfc.html
But I found that I had to override the function onNewIntent, with code like this:
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
String uri = intent.getDataString();
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];
}
}
}
For me, all I needed was:
String uri = intent.getDataString();
Good luck!
You can listen for all tags activated using the ACTION_TAG_DISCOVERED intent, rather than filtering for a specific one with the following code:
public NFCForegroundUtil(Activity activity)
{
super();
this.activity = activity;
mAdapter = NfcAdapter.getDefaultAdapter(activity
.getApplicationContext());
mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(
activity, activity.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
// See below
mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
From the NFCAdapter Documentation :
If you pass null for both the filters and techLists parameters that acts a wild card and will cause the foreground activity to receive all tags via the ACTION_TAG_DISCOVERED intent.
Your problem is when you initialise the intent i onNewIntent
The class should be itself, not the second class.
The right code should be :
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
Intent i = new Intent(this, NfcDisplayLabelActivity1.class);
startActivity(i);
}
I was seeing "New tag collected" from build-in app called "Tags" because my application didn't work properly.
When it works ok, it has higher priority than "Tags" and phone reads tags from my application. But when it works unproperly and phone collect a tag, "Tags" application is activated and "Tags" application talks to my device.
After repairing code, my app has higher priority and phone reads tags using my application.

Categories