I am trying to open a new "activity" (C2M) in an Android app, and in that new activity open a socket with the ip address and port coming from the previous "activity" (called MeasActivity).
I have checked that the ip and address are correctly gotten in C2M (as strings), but the socket can not be created.
Part of the code is the following:
public class C2M extends Activity {
Socket socket;
private String serverIpAddress;
private String serverPort;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmeas);
intentback = new Intent(this, MeasActivity.class);
Intent intent = getIntent();
serverIpAddress = intent.getStringExtra(MeasActivity.EXTRA_IP);
serverPort = intent.getStringExtra(MeasActivity.EXTRA_PORT);
try {
socket = new Socket(serverIpAddress, Integer.parseInt(serverPort));
} catch (Exception e) {
startActivity(intentback);
}
}
}
Also, the manifest file is the following:
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MeasActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="C2M"></activity>
</application>
I am not sure if I missing something, but as I said, I have issues creating the socket.
Thanks in advance for the help and advice you can provide.
gus
Related
Android launch application multiple times on an NFC tag discovered. I tried using the answer in this link Android launch activity multiple times on an NFC tag. but it says resources not found.
I am reading the tag from a fragment. Any help.
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.atsl.touch">
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-feature android:name="android.hardware.nfc" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:launchMode= "singleInstance"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
this is my fragments onResume()
public void onResume() {
super.onResume();
Intent intent =getActivity().getIntent();
pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, 0);
intentFilter = new IntentFilter[] { };
nfcAdapter = NfcAdapter.getDefaultAdapter(getContext());
String action = intent.getAction();
boolean cardMatched=false;
Tag tag=null;
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Toast.makeText(getContext(),"Blahhhhh",Toast.LENGTH_LONG).show();
tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
tappedCard=new Card();
tappedCard.setCardId(MainActivity.bytesToHexString(tag.getId()));
//tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
////////////+___________________________________________
////////////+___________________________________________
if(tag == null){
Toast.makeText(getContext(), "tag == null",Toast.LENGTH_SHORT).show();
}else{
Card cc=new Card();
String tagId= MainActivity.bytesToHexString(tag.getId());
cc.setCardId(tagId);
dbHelper=new DBHelper(getContext());
ArrayList<Card> checkList=dbHelper.getAllCards();
if(checkList.size()>0)
{
for(Card d:checkList)
{
if (cc.equals(d))
{
cardMatched=true;
Toast.makeText(getContext(), "Card Matched !!!!",Toast.LENGTH_SHORT).show();
showCardDetails(cc.getCardId());
break;
}
else
{
continue;
}
}
if (!cardMatched)
{
imgBusCard.setVisibility(View.GONE);
showDetails.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Card Not Matched !!!!",Toast.LENGTH_SHORT).show();
CustomDialogAddCard customDialogAddCard =new CustomDialogAddCard(getActivity(),"T",cc);
customDialogAddCard.show();
showCardDetails(cc.getCardId());
}
}
else {
Toast.makeText(getContext(), "No cards found !!!!",Toast.LENGTH_SHORT).show();
CustomDialogAddCard customDialogAddCard =new CustomDialogAddCard(getActivity(),"T",cc);
customDialogAddCard.show();
showCardDetails(cc.getCardId());
}
}
}else{
Toast.makeText(getContext(),
"onResume() : " + action,
Toast.LENGTH_SHORT).show();
}
}
The problem is when i run the application and hold an nfc tag near the phone app starts a new instance of the application. it doesn't detect the tag in the initial instance.
This question already has answers here:
How to use NFC ACTIONS
(5 answers)
Closed 3 years ago.
I'm creating application that do some action if hit NFC chip , I know the following information about NFC in Android please correct me if I am wrong
you can't register actions of the NFC to receiver in the manifest file , only activities .
each NFC chip has it's own unique id .
what I want to do is
while the Application is in the background or it's closed , if I hit NFC chip with id (ex 1234) my app lunched and do some action.
is that possible ?
if yes, how it can be achieved?
edit
here is my code , it does open when you check any NFC chip and get this action android.nfc.action.TECH_DISCOVERED
but when it open the action is android.intent.action.MAIN
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String ACTION_CHECK_IN= "checked";
public static final String ACTION_CHECK_OUT= "unchecked";
private NfcAdapter mNfcAdapter;
boolean isCheckedIn = false;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
isCheckedIn = Pref.getBoolean("check", false);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called with: " + "");
String action = getIntent().getAction();
if (action != null) {
Log.d("MainActivity", "onCreate(" + action + ")");
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED) || action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) || action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
if (!isCheckedIn) {
isCheckedIn = true;
Pref.putBoolean("check", true);
Log.d("checking","IN");
} else {
isCheckedIn = false;
Pref.putBoolean("check", false);
Log.d("checking","Out");
}
}
}
if (!mNfcAdapter.isEnabled()) {
Toast.makeText(MainActivity.this, "Please open it ", Toast.LENGTH_SHORT).show();
}
/**
* It's important, that the activity is in the foreground.
* Otherwise an IllegalStateException is thrown.
*/
setupForegroundDispatch(this, mNfcAdapter);
}
#Override
protected void onPause() {
/**
* Call this before onPause, otherwise an IllegalArgumentException is thrown.
*/
stopForegroundDispatch(this, mNfcAdapter);
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public static void setupForegroundDispatch(Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(
activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[2];
String[][] techList = new String[][]{};
// same filter as manifest - action, category
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filters[1] = new IntentFilter();
filters[1].addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public static void stopForegroundDispatch(Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.srjo.pocnfcadapter">
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/filter_nfc" />
</activity>
</application>
</manifest>
According the the Android Developer site, it is possible for your app to filter NFC intents such as ACTION_NDEF_DISCOVERED.
First register your app in the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.survivingwithandroid.nfc" >
....
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain"/>
</intent-filter>
<manifest>
Then you should use foreground dispatch (foreground app). Finally you use NFCAdapter to read the content (onNewIntent).
I wrote a detailed posts about NFC if you like give a look.
I am creating an app where two devices communicate over NFC and then one transmits to the server.
I am trying to develop this for both pre- and post-lollipop. The problem is that I create my NDEF message in one app and then receive it in another app. However when I try to receive in the other app, the NFC "New Tag collected" screen is opened instead of my app. This is a real problem for me, I'm just sending a string which I need to send to a web service.
Below is the manifest of the receiving application:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.devcompany.paymentcustomer" >
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activities.HomeActivity"
android:launchMode="singleTop"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is my code for sending:
mNfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
//If device is running lollipop remove the touch to beam action
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mNfcAdapter.setNdefPushMessageCallback(nDefCallback, getActivity());
mNfcAdapter.invokeBeam(getActivity());
}
}, 2000);
}else{
//leave touch to beam action
mNfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
NdefMessage message = new NdefMessage((new NdefRecord[]{createMime("application/com.devcompany.paymentvendor.fragments", mToBeam.getBytes()) }));
return message;
}
}, getActivity());
mNfcAdapter.setOnNdefPushCompleteCallback(
new NfcAdapter.OnNdefPushCompleteCallback() {
#Override
public void onNdefPushComplete(NfcEvent event) {
}
}, getActivity());
}
Here is my code for receiving:
public class HomeActivity extends ActionBarActivity {
private NfcAdapter mAdapter;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_layout);
mAdapter = NfcAdapter.getDefaultAdapter(this);
textView = (TextView)findViewById(R.id.fortressLabel);
}
#Override
public void onResume(){
super.onResume();
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
private void processIntent(Intent intent){
//textView.setText(intent.getDataString());
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
Log.i(this.getLocalClassName(), intent.getDataString());
}
}
I have debugged my receiving code and stepped through it, when I hold the phones together, the code doesn't even enter the onResume method. The tags intent is launched first. I don't understand why this is happening. Can anyone help me on this one?
You are sending a MIME type record of type "application/com.devcompany.paymentvendor.fragments":
NdefMessage message = new NdefMessage(new NdefRecord[] {
NdefRecord.createMime("application/com.devcompany.paymentvendor.fragments",
mToBeam.getBytes())
});
Consequently, you also need to instruct your receiving activity to actually receive that MIME type record. You can register your app to open (and receive) upon detection of that MIME type in an NFC event by adding an NDEF_DISCOVERED intent filter for your activity:
<activity android:name=".activities.HomeActivity" ...>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="application/com.devcompany.paymentvendor.fragments" />
</intent-filter>
</activity>
I have USB host android device for that I need to connect USB device. to detect usb device to host I written following code.
public class ReadData extends Activity {
UsbManager usbManager;
PendingIntent mPermissionIntent;
UsbDevice usbDevice;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_data);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
final String ACTION_USB_PERMISSION =
"com.example.udevice.USB_PERMISSION";
IntentFilter filter = new IntentFilter("android.hardware.usb.action.USB_ACCESSORY_ATTACHED");
registerReceiver(mUsbReceiver, filter);
}
private static final String ACTION_USB_PERMISSION =
"com.example.udevice.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
usbManager.requestPermission(usbDevice, mPermissionIntent);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(usbDevice != null){
//call method to set up device communication
int deviceId = usbDevice.getDeviceId();
int productId = usbDevice.getProductId();
Log.i("device id", "****"+deviceId);
Log.i("product id", "****"+productId);
}else{
Log.i("device id", "No USB device");
}
}
else {
Log.d("shiv", "permission denied for device ");
}
}
}
}
};
and manifest is like below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udevice"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ReadData"
android:label="#string/title_activity_heat_con" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
</activity>
</application>
</manifest>
device_filter.xml
<resources>
<usb-device vendor-id="67b"
product-id="2303"/>
</resources>
in above xml file I added device attributes. I am expecting a broadcast intent whenever USB device connected to host device. but it is not happening. What is wrong with above code.
Thanks
shiv
I think you need to add:
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
It is described here
There is onething you are doing it wrong.
The vendor id and device id should be in decimals not in hex. For example, you need to define as follows
<resources>
<usb-device vendor-id="1659"
product-id="8963"/>
</resources>
I converted your device id and vendor-id from hex to decimal
Let me know if this helps
I try to play with Service in Android, my application contain an Activity with a button so that it can do action when I press it.
The core component is the ExtractingURLService , which extends IntentService framework class.
I have overrided the onHandleIntent() method, so that it can handle intent passed to it properly.
Code:
public class ExtractingURLService extends IntentService {
private static final String TAG = "ExtractingURLService";
public ExtractingURLService(String name) {
super("ExtractingURLService");
}
#Override
protected void onHandleIntent(Intent intent) {
// do something here !
}
}
}
The Android Manifest file is :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.service.urlextraction"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".ServiceExample02Activity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ExtractingURLService" android:enabled="true"></service>
</application>
</manifest>
In my only Activity class, I call the service by using:
Intent startServiceIntent = new Intent(this, ExtractingURLService.class);
startService(startServiceIntent);
That's all my work, but when deploy, the runtime error I received was:
04-09 16:24:05.751: ERROR/AndroidRuntime(1078): Caused by:
java.lang.InstantiationException:
example.service.urlextraction.ExtractingURLService
What I should do with that ??
Add full path of Service
<service android:name="com.foo.services.ExtractingURLService" android:enabled="true"></service>
Intent Service should look like this:
package com.foo.services;
import android.app.IntentService;
import android.content.Intent;
public class ExtractingURLService extends IntentService {
private static final String TAG = "ExtractingURLService";
public ExtractingURLService() {
super("ExtractingURLService");
}
#Override
protected void onHandleIntent(Intent intent) {
// do something here !
}
}
You can add try and catch block to avoid crash.Its work for me
try {
Intent intent = new Intent(DashboardActivity.this, MyService.class);
startService(intent);
}catch (IllegalStateException e){
}catch (Exception ee){
}