Self-managed connection service callbacks aren't invoked on Samsung devices - android

I develop a VoIP app using this guide.
I faced the problem with a self-manged connection service on Samsung devices.
I'm placing a call using TelecomManager.
I expect that ConnectionService::onCreateOutgoingConnection or ConnectionService::onCreateOutgoingConnectionFailed will be invoked, but it doesn't happen on some Samsung devices.
After placing a call the dialog window appears. On samsung galaxy s10 an android toast appears with the text "Call not sent". Methods of connection service are not invoked.
On phones with the vanilla Android it works as expected.
Does anybody know how to solve this issue?
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tcom">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.tcom.ConnectionService"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
</manifest>
ConnectionService:
public class ConnectionService extends android.telecom.ConnectionService {
private static final String TAG = "ConnectionService";
#Override
public android.telecom.Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnectionFailed");
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public android.telecom.Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnectionFailed");
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
}
Connection:
public class Connection extends android.telecom.Connection {
private static final String TAG = "Connection";
public Connection() {
super();
setConnectionProperties(android.telecom.Connection.PROPERTY_SELF_MANAGED);
}
#Override
public void onStateChanged(int state) {
super.onStateChanged(state);
Log.i(TAG, "onStateChanged state=" + android.telecom.Connection.stateToString(state));
}
}
PhoneAccount creating:
void createAccount() {
tm = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
if (tm == null) {
throw new RuntimeException("cannot obtain telecom system service");
}
ComponentName connectionServiceName = new ComponentName(getApplicationContext(), ConnectionService.class);
PhoneAccountHandle accountHandle = new PhoneAccountHandle(connectionServiceName, PHONE_ACCOUNT_LABEL);
try {
PhoneAccount phoneAccount = tm.getPhoneAccount(accountHandle);
if (phoneAccount == null) {
PhoneAccount.Builder builder = PhoneAccount.builder(accountHandle, PHONE_ACCOUNT_LABEL);
builder.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED);
phoneAccount = builder.build();
tm.registerPhoneAccount(phoneAccount);
}
this.accountHandle = phoneAccount.getAccountHandle();
if (tm.getPhoneAccount(accountHandle) == null) {
throw new RuntimeException("cannot create account");
}
} catch (SecurityException e) {
throw new RuntimeException("cannot create account", e);
}
}
Call creating:
void createCall() {
try {
Bundle extras = new Bundle();
extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, accountHandle);
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, "test_call", null);
tm.placeCall(uri, extras);
}
catch (SecurityException e) {
throw new RuntimeException("cannot place call", e);
}
}

After some firmware update the code above started working correctly.
So, the problem was in the phone itself.

Anybody else having this problem, just make sure of two things:
Remove PhoneAccount.CAPABILITY_CALL_PROVIDER from your phone account's capabilities.
You have implemented an InCallService.

Related

How to receive USB connection status broadcast?

I am trying to detect USB connection in my app, that is, whether or not USB is connected to device.
It's being tested on Marshmallow 6.0.1 (sdk23)
But I'm unable to receive the broadcast actions ACTION_USB_DEVICE_ATTACHED or ACTION_USB_DEVICE_DETACHED..
I tried using both the dynamic way and the AndroidManifest.xml way, neither worked..
Here's my code:
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gokulnc.blah_blah"
android:installLocation="auto"
android:versionCode="15"
android:versionName="1.5.1">
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<android:uses-permission android:name="android.permission.USB_PERMISSION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:vmSafeMode="false">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/DrawerTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver android:name="mUsbReceiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
</receiver>
</activity>
</application>
</manifest>
MainActivity.java :
public class MainActivity extends AppCompatActivity {
BroadcastReceiver mUsbReceiver;
public void onCreate(Bundle savedInstanceState) {
.....
setBroadcastReceivers();
}
void setBroadcastReceivers() {
//Reference: http://www.codepool.biz/how-to-monitor-usb-events-on-android.html
mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(LOG_TAG, "Received Broadcast: "+action);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
updateUSBstatus();
Log.d(LOG_TAG, "USB Connected..");
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action) || UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
updateUSBstatus();
}
Log.d(LOG_TAG, "USB Disconnected..");
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
//filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
//filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver , filter);
Log.d(LOG_TAG, "mUsbReceiver Registered");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "App Resumed..");
//Refernce: https://stackoverflow.com/questions/18015656/cant-receive-broadcast-intent-of-usbmanager-action-usb-device-attached-usbmanag
Intent intent = getIntent();
if (intent != null) {
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
Toast.makeText(getApplicationContext(), "Attached", Toast.LENGTH_SHORT).show();
} else if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Toast.makeText(getApplicationContext(), "Detached", Toast.LENGTH_SHORT).show();
}
}
}
}
I also checked this answer: Can't receive broadcast Intent of UsbManager.ACTION_USB_DEVICE_ATTACHED/UsbManager.ACTION_USB_DEVICE_DETACHED, but it didn't help..
Can someone please point out where I'm wrong??
Maybe the reason it doesn't work is that since Android 6.0, the default USB mode is Charging and, maybe ACTION_USB_DEVICE_ATTACHED doesn't get fired up when connected in that mode..
Instead, now I have another solution:
String usbStateChangeAction = "android.hardware.usb.action.USB_STATE";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(LOG_TAG, "Received Broadcast: "+action);
if(action.equalsIgnoreCase(usbStateChangeAction)) { //Check if change in USB state
if(intent.getExtras().getBoolean("connected")) {
// USB was connected
} else {
// USB was disconnected
}
}
}
That is, the broadcast android.hardware.usb.action.USB_STATE is sent whenever there is a toggle in the USB state.
Unlike android.hardware.usb.action.USB_DEVICE_ATTACHED which is broadcasted only when something like a MTP mode is enable, android.hardware.usb.action.USB_STATE is broadcasted whenever it detects an USB connection that's capable of connecting to a host (say computer), irrespective of its current USB Mode like Charging, MTP or whatever.. (it's called USB config to be more precise)
Here the perfect steps to check that external usb connection occur or not in android activity. Just Follow the steps one by one.
In Android Manifest file:
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
Inside your USB checking Activity Tag:
<activity android:name=".USBEnabled">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
</activity>
Inside your connectivity checking USBEnabled class :
public class USBEnabled extends AppCompatActivity {
private static final String TAG = "UsbHost";
TextView mDeviceText;
Button mConnectButton;
UsbManager mUsbManager;
UsbDevice mDevice;
PendingIntent mPermissionIntent;
private static final int REQUEST_TYPE = 0x80;
private static final int REQUEST = 0x06;
private static final int REQ_VALUE = 0x200;
private static final int REQ_INDEX = 0x00;
private static final int LENGTH = 64;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_usbenabled);
mDeviceText = (TextView) findViewById(R.id.text_status);
mConnectButton = (Button) findViewById(R.id.button_connect);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
}
#Override
protected void onRestart() {
super.onRestart();
recreate();
}
#Override
protected void onResume() {
super.onResume();
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
updateDeviceList();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
}
public void onConnectClick(View v) {
if (mDevice == null) {
return;
}
mUsbManager.requestPermission(mDevice, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION = "com.android.recipes.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)) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
&& device != null) {
getDeviceStatus(device);
} else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
};
private void getDeviceStatus(UsbDevice device) {
UsbDeviceConnection connection = mUsbManager.openDevice(device);
byte[] buffer = new byte[LENGTH];
connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX,
buffer, LENGTH, 2000);
connection.close();
}
private void updateDeviceList() {
HashMap<String, UsbDevice> connectedDevices = mUsbManager
.getDeviceList();
if (connectedDevices.isEmpty()) {
mDevice = null;
mDeviceText.setText("No Devices Currently Connected");
mConnectButton.setEnabled(false);
} else {
for (UsbDevice device : connectedDevices.values()) {
mDevice = device;
}
mDeviceText.setText("USB Device connected");
mConnectButton.setEnabled(true);
}
}}
Inside your class xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onConnectClick"
android:text="Connect" />
<TextView
android:id="#+id/text_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="22dp" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="22dp" />
</LinearLayout>
Now create a new resource directory called xml and create new xml file called device_filter.xml with the following code.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device />
</resources>
Debug and run the application, it will show external usb device connectivity status without any error. I hope you will get output for your scenario.
Enjoy!!

AIDL service not connecting after bindService()

I am trying to develop a setup of 2 applications (service app + client app) using AIDL. I have currently a setup of 3 modules:
android-agent-framework (android library module holding only the AIDL file)
android-agent (the service)
android-example-client (the client)
android-agent and android-agent-framework have a dependency to the first one to get access to the interface.
Whenever the client calls bindService() it gets false as return and in the ServiceConnection the onServiceConnected() is not called. Also in the service implementation the onBind() is not called. There is no error in the logs.
Here is the code:
android-agent activity:
public class MyCompanyStartActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(MyCompanyStartActivity.class.toString(), "Create MyCompanyStartActivity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ComponentName service = startService(new Intent(this, MyCompanyRequestService.class));
Log.i("tag", service.getClassName() + "::" + service.getPackageName());
}
}
android-agent service:
public class MyCompanyRequestService extends Service {
#Override
public IBinder onBind(Intent intent) {
Log.i(MyCompanyRequestService.class.toString(), "Starting SmartRest Service");
return mBinder;
}
private final IMyCompanyRequestService.Stub mBinder = new IMyCompanyRequestService.Stub() {
#Override
public void sendData(String xid, String authentication, String data) throws RemoteException{
Log.i(MyCompanyRequestService.class.toString(), "sending data: " + data);
}
};
}
android-agent manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.android.agent" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MyCompanyStartActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Services -->
<service
android:name="com.mycompany.android.agent.framework.MyCompanyRequestService"
android:process=":remote"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="MyCompanyRequestService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
<!-- Permissions -->
</application>
</manifest>
android-example-client activity:
public class ClientStarter extends Activity {
protected IMyCompanyRequestService mycompanyRequestService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("tag","create client");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
if (mycompanyRequestService == null) {
printServices();
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent.framework");
Log.i("tag","before binding service: " + it.getAction() + "::" + it.getPackage());
boolean serviceBinding = getApplicationContext().bindService(it, connection, Context.BIND_AUTO_CREATE);
Log.i("tag", "service is bound: " + serviceBinding);
}
Handler handler = new Handler();
handler.postDelayed(new Runner(), 10000);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("service", "Service connected");
mycompanyRequestService = IMyCompanyRequestService.Stub.asInterface(service);
Toast.makeText(getApplicationContext(), "Service Connected", Toast.LENGTH_SHORT).show();
Log.i("service", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i("service", "Service disconnected");
mycompanyRequestService = null;
Toast.makeText(getApplicationContext(), "Service Disconnected", Toast.LENGTH_SHORT).show();
Log.i("service", "Service disconnected");
}
};
private void printServices() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
Log.d("service", service.service.getClassName());
}
}
private class Runner implements Runnable {
#Override
public void run() {
Log.i("tag","starting");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
} while(true) {
try {
if (mycompanyRequestService != null) {
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i(ClientStarter.class.toString(), loc.getLatitude() + " - " + loc.getLongitude() + " - " + loc.getAltitude());
mycompanyRequestService.sendData("test", "auth", String.valueOf(loc.getLatitude()) + "," + String.valueOf(loc.getLongitude()) + "," + String.valueOf(loc.getAltitude()));
} else {
Log.i(ClientStarter.class.toString(), "service not yet available");
}
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
} catch (RemoteException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
}
}
}
}
}
The printServices() call before trying to bind the service actually lists the service so it is running.
The log does not contain any errors and the client is in the end running in the loop but the service is still null.
Maybe someone encountered a similar issue before.
After going another round through all files I found my mistake.
I needed to change:
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent.framework");
to:
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent");
The package of the Intent needs to match the package of the app and not the package of the service.
Another reason why you could face this issue (at least I did) is that – from API level 30 – you are also required to declare the apps that you communicate to in the manifest, for example:
<queries>
<package android:name="com.your.app" />
</queries>

Testing an app by faking NFC tag scan

I am new to Android, working on Near Field Communication for reading data from NFC tags. Neither I have NFC supported Android mobile nor NFC tags to test the application I created.
I found the below two posts which says about faking NFC tag scans by triggering an Intent.
Possibility for Fake NFC(Near Field Communication) Launch
Need To Fake an NFC Tag Being Scanned In Android
I changed my code according to the first post, where on click of a button I am triggering the required Intent in the 1st activity. Whereas I have created one more activity capable of handling that same intent. The reading of NFC tag and handling data is based on a button click on the 2nd activity.
The problem is: Whenever I am triggering the fake NFC tag scan intent from the 1st activity, it is throwing an error "No Activity found to handle Intent { act=android.nfc.action.NDEF_DISCOVERED (has extras) }".
The Manifest file goes like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.expensemanager.saubhattacharya">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.NFC"/>
<uses-feature android:name="android.hardware.nfc" android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/icon1"
android:label="#string/app_name"
android:supportsRtl="true"
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>
</activity>
<activity
android:name=".Set_Monthly_Target"
android:label="#string/title_activity_set__monthly__target"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.expensemanager.saubhattacharya.MainActivity" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<activity
android:name=".Add_Daily_Expense"
android:label="#string/add_daily_expense_activity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.expensemanager.saubhattacharya.MainActivity" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*" />
</intent-filter>
</activity>
</application>
</manifest>
The intent trigger code snippet from the 1st activity is below:
public void scan_tag (View view)
{
final Intent intent = new Intent(NfcAdapter.ACTION_NDEF_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, "Custom Messages");
startActivity(intent);
}
The code snippet from the 2nd activity, which handles the above trigger is below:
public class Add_Daily_Expense extends AppCompatActivity {
Button read_data;
TextView show_data;
Tag detected_tag;
NfcAdapter nfcAdapter;
IntentFilter[] intentFilters;
public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String MIME_IMAGE_ALL = "image/*";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__daily__expense);
final PackageManager pm = this.getPackageManager();
show_data = (TextView) findViewById(R.id.show_data);
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
read_data = (Button) findViewById(R.id.read_nfc);
read_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
try {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Daily_Expense.this);
builder.setMessage("NFC feature is not available on this device!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "NFC feature is available on this device!", Toast.LENGTH_SHORT).show();
HandleIntent(getIntent());
}
}
});
}
public void HandleIntent(Intent intent)
{
String action = intent.getAction();
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
{
detected_tag = getIntent().getParcelableExtra(nfcAdapter.EXTRA_TAG);
NDefReaderTask NDefReader = new NDefReaderTask();
NDefReader.execute();
}
}
public void onResume()
{
super.onResume();
if(nfcAdapter != null)
setupForeGroundDispatch(this, nfcAdapter);
}
public void onPause()
{
super.onPause();
if(nfcAdapter != null)
stopForeGroundDispatch(this, nfcAdapter);
}
public void onNewIntent(Intent intent)
{
HandleIntent(intent);
}
public void setupForeGroundDispatch (final Activity activity, NfcAdapter nfcAdapter)
{
Intent new_intent = new Intent(getApplicationContext(),Add_Daily_Expense.class);
new_intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,new_intent,0);
intentFilters = new IntentFilter[1];
String[][] techList = new String[][]{};
intentFilters[0] = new IntentFilter();
intentFilters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
intentFilters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
intentFilters[0].addDataType(MIME_TEXT_PLAIN);
intentFilters[0].addDataType(MIME_IMAGE_ALL);
}
catch(IntentFilter.MalformedMimeTypeException me)
{
me.printStackTrace();
}
nfcAdapter.enableForegroundDispatch(activity, pendingIntent, intentFilters, techList);
}
public void stopForeGroundDispatch (final Activity activity, NfcAdapter nfcAdapter)
{
nfcAdapter.disableForegroundDispatch(activity);
}
public class NDefReaderTask extends AsyncTask <Tag, Void, String>
{
#Override
protected String doInBackground(Tag... params)
{
try
{
detected_tag = params[0];
Ndef ndef = Ndef.get(detected_tag);
ndef.connect();
if(ndef != null)
{
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
NdefRecord[] records = ndefMessage.getRecords();
for(NdefRecord ndefRecord : records)
{
if((ndefRecord.getTnf() == NdefRecord.TNF_ABSOLUTE_URI) || (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN))
{
byte[] payload = ndefRecord.getPayload();
String encoding1 = "UTF-8";
String encoding2 = "UTF-16";
String textEncoding = ((payload[0] & 128) == 0) ? encoding1 : encoding2;
int languageCodeLength = payload[0] & 0063;
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
}
}
ndef.close();
}
catch (UnsupportedEncodingException UE)
{
UE.printStackTrace();
}
catch (IOException IE)
{
IE.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute()
{
}
protected void onPostExecute(String result)
{
if(result != null)
{
show_data.setText(result);
}
}
}
}
My question is: What is wrong I am doing here? Is there any other way to test my app by faking the NFC tag scan?
You specify a MIME type filter for the NDEF_DISCOVERED intent filter:
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*" />
Consequently, the fake NFC intent needs to contain one of these MIME types to match the intent filter. You can add the type information to the intent using the setType() method:
public void scan_tag (View view) {
final Intent intent = new Intent(NfcAdapter.ACTION_NDEF_DISCOVERED);
intent.setType("text/plain");
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, ...);
startActivity(intent);
}
Also note that the above code won't add a tag handle to the NFC intent. Hence, you can't obtain a Tag object with
detected_tag = getIntent().getParcelableExtra(nfcAdapter.EXTRA_TAG);
Consequently, you also can't obtain an instance of the Ndef connection class using
Ndef ndef = Ndef.get(detected_tag);
You might want to look into the following questions/answers regarding mock tag objects:
How to mock a Android NFC Tag object for unit testing
Is there a way to create an ACTION_NDEF_DISCOVERED intent from code
How to simulate the tag touch from other application
Finally, be aware that there are several other issues in your code.

Application with Internet for the main and without for the rest

I have an app in which starting page needs internet,
Rest want to work without internet (ie, only one activity need the internet permission).
But when I turn off the Internet, the app shows a message like turn internet connection on and then only I can proceed to further (Here i want to work with out internet).
Is there any solution for that?
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exampleMock.ibps_test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="landscape" >
<activity
android:name="com.exampleMock.ibps_test.MainActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.exampleMock.ibps_test.testClass"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.startTest"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.resultActivity"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showDialog"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showSolution"
android:label="#string/app_name"
android:screenOrientation="landscape" />
<activity
android:name="com.exampleMock.ibps_test.InfoGift"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
</application>
Main Activity:
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Void>, AsyncHttpRequestDelegate
{
static EditText n;
static EditText p;
ProgressBar pb;
static String mail="";
private DatabaseHelper helper;
private SQLiteDatabase db;
private static WeakReference<MainActivity> mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new DatabaseHelper(this);
helper.initializeDataBase();
db=helper.getWritableDatabase();
String stat=check();
if(stat.equals("true"))
{
gotoNextPage();
}
else
{
n=(EditText)findViewById(R.id.name);
p=(EditText)findViewById(R.id.phone);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
mail=fetchEmail();
/*
if(mail==null)
{
EditText m=(EditText)findViewById(R.id.mail);
m.setVisibility(1);
mail=m.getText().toString();
} */
Button b=(Button)findViewById(R.id.regBtn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(n.getText().toString().length()<1)
{
n.requestFocus();
Toast.makeText(MainActivity.this, "Enter your Name", Toast.LENGTH_SHORT).show();
}
else if(p.getText().toString().length()<10)
{
p.requestFocus();
Toast.makeText(MainActivity.this, "Enter a valid phone number", Toast.LENGTH_SHORT).show();
}
else
{
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
pb.setVisibility(View.VISIBLE);
//call asyncTask
startWork();
} else {
Toast.makeText(MainActivity.this, "No Network connection available...",Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
public String fetchEmail()
{
String e="";
Pattern email= Patterns.EMAIL_ADDRESS;
Account[] accounts= AccountManager.get(this).getAccounts();
for(Account account:accounts)
{
if(email.matcher(account.name).matches())
{
e=account.name;
return e;
}
}
return null;
}
public String check()
{
String flag="";
String sql="select * from reg_status";
Cursor c=db.rawQuery(sql, null);
if(c!=null)
{
c.moveToFirst();
flag=c.getString(0);
}
return flag;
}
public void updateStatus()
{
String sql="update reg_status set status = 'true'";
db.execSQL(sql);
gotoNextPage();
}
public void gotoNextPage()
{
Intent intent=new Intent(this,startTest.class);
startActivity(intent);
}
void startWork() {
getSupportLoaderManager().initLoader(0, (Bundle) null, this);
}
static class AsyncTaskMaker extends AsyncTaskLoader<Void> {
int progress = 0;
int percentProgress = 0;
int fileLength = 0;
AsyncTaskMaker(MainActivity activity) {
super(activity);
mActivity = new WeakReference<MainActivity>(activity);
}
#Override
public Void loadInBackground() {
System.out.println("inside loadInBackground");
processWebRequest();
return null;
}
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Void> arg0,
Void arg1) {
pb.setVisibility(View.GONE);
updateStatus();
//Toast.makeText(MainActivity.this, "Load finished", Toast.LENGTH_SHORT).show();
gotoNextPage();
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Void> arg0) {
//Toast.makeText(MainActivity.this, "Load reset", Toast.LENGTH_SHORT).show();
}
#Override
public android.support.v4.content.Loader<Void> onCreateLoader(int arg0, Bundle arg1) {
AsyncTaskMaker asyncTaskLoader = new AsyncTaskMaker(this);
asyncTaskLoader.forceLoad();
return asyncTaskLoader;
}
private static void processWebRequest(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://beta.wisdom24x7.com/gapps.php/");
//System.out.println("inside processWebRequest");
try
{
List<NameValuePair> pair=new ArrayList<NameValuePair>(4);
pair.add(new BasicNameValuePair("name",n.getText().toString()));
pair.add(new BasicNameValuePair("email",mail));
pair.add(new BasicNameValuePair("phone",p.getText().toString()));
pair.add(new BasicNameValuePair("exam","AIEEE"));
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse= httpclient.execute(httpPost);
Log.d("Http Response:", httpResponse.toString());
}catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void didComplete(HttpRequest request, String responseString) {
pb.setVisibility(View.GONE);
//Toast.makeText(MainActivity.this, "data sent", Toast.LENGTH_SHORT).show();
}
#Override
public void didFail(HttpRequest request) {
}
#Override
public void publishProgress(final int progress) {
if (mActivity.get() != null) {
mActivity.get().runOnUiThread(new Runnable() {
#Override
public void run() {
mActivity.get().pb.setProgress(progress);
}
});
}
}
}
Another activity, which does not require internet:
public class showDialog extends ActionBarActivity
{
CheckBox b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_sub);
b1=(CheckBox)findViewById(R.id.checkBox1);
b2=(CheckBox)findViewById(R.id.checkBox2);
b3=(CheckBox)findViewById(R.id.checkBox3);
b4=(CheckBox)findViewById(R.id.checkBox4);
final List<String> subs=new ArrayList<String>();
ImageButton bn=(ImageButton)findViewById(R.id.imageButton1);
bn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(b1.isChecked())
subs.add(b1.getText().toString());
if(b2.isChecked())
subs.add(b2.getText().toString());
if(b3.isChecked())
subs.add(b3.getText().toString());
if(b4.isChecked())
subs.add(b4.getText().toString());
System.out.print("subjects "+subs);
Intent intent = new Intent(showDialog.this,testClass.class);
intent.putStringArrayListExtra("subject", (ArrayList<String>) subs);
startActivity(intent);
}
});
}
}
It seems you didn't write this Android application by yourself (or else you would understand what the message means). This message that "asks for internet connection" is something that is done through your app and not by the Android framework. Please understand your application first, then ask questions about it.
Hint: Search for the String inside your app (by search functionality of your IDE) that is shown in your "asks for internet connection" message and look up why it is displayed. You will see, that you can disable it.
in your AndroidManifest.xml put :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
and inonCreate method of each activity you don't want to use the internet_connection in:
WifiManager wifiManager = (WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
You can only set permission for the complete app, not on single activity.
Why is it so important that the user doesn't have an internet connection in the rest of the app? When you don't code anything that connects to the internet in those "internet-free" activities, then you won't use up the (possible) date

Why onPushMessageReceived() is not called in Geoloqi API in Android?

In my android app i am using Latest Geoloqi API to implement Geofence concept.when user entered into some region he has notify, for that purpose i am using Push Notifications.in GeoReceiver class three callback methods are calling but not onPushMessageReceived().please help me how to do it?
I am creating trigger with current location is it required to enter into region manually or since i am already in the location its not calling?
Note:I ve given required credentials in assets/geoloqi.properties file.when app is launched in logcat "Successfully registered for the C2DM service" msg also displayed.my code:
GeoloqiExampleActivity.java
public class GeoloqiExampleActivity extends Activity{
String TAG = "Geoloqi Example";
private LQService mService;
private boolean mBound;
GeoReceiver geoReceiver = new GeoReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, LQService.class);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
// Bind to the tracking service so we can call public methods on it
Intent intent = new Intent(this, LQService.class);
bindService(intent, mConnection, 0);
// Wire up the sample location receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(GeoReceiver.ACTION_LOCATION_CHANGED);
filter.addAction(GeoReceiver.ACTION_TRACKER_PROFILE_CHANGED);
filter.addAction(GeoReceiver.ACTION_LOCATION_UPLOADED);
filter.addAction(GeoReceiver.ACTION_PUSH_MESSAGE_RECEIVED);
registerReceiver(geoReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
// Unbind from LQService
if (mBound) {
unbindService(mConnection);
mBound = false;
}
// Unregister our location receiver
unregisterReceiver(geoReceiver);
}
public void sendRequest() {
// Performing a Trigger POST request
if (mService != null) {
LQSession session = mService.getSession();
LQTracker tracker = mService.getTracker();
tracker.setSession(session);
// Build your request
JSONObject trigger = new JSONObject();
try {
trigger.put("text", "Popcornapps");
trigger.put("type", "message");
trigger.put("latitude", 17.42557068);
trigger.put("longitude", 78.42022822);
trigger.put("radius", 500);
trigger.put("place_name", "Banjara Hills");
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
// Send the request
session.runPostRequest("trigger/create", trigger, new OnRunApiRequestListener() {
#Override
public void onSuccess(LQSession session, HttpResponse response) {
Toast.makeText(GeoloqiExampleActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
String result = s.toString().trim();
Log.d("On success Result", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(LQSession session, LQException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(GeoloqiExampleActivity.this, "Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(LQSession session, HttpResponse response, StatusLine status) {
Toast.makeText(GeoloqiExampleActivity.this, "Complete", Toast.LENGTH_LONG).show();
}
});
} else{
Toast.makeText(this, "service null", Toast.LENGTH_LONG).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
LQBinder binder = (LQBinder) service;
mService = binder.getService();
mBound = true;
sendRequest();//Sending API Request
} catch (ClassCastException e) {
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
GeoReceiver.java
public class GeoReceiver extends LQBroadcastReceiver {
#Override
public void onLocationChanged(Context arg0, Location arg1) {
Toast.makeText(arg0, "Loc Changed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPushMessageReceived(Context context, Bundle data) {
Toast.makeText(context, "Push Msg Received ", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationUploaded(Context arg0, int arg1) {
Toast.makeText(arg0, "Location Uploaded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onTrackerProfileChanged(Context arg0, LQTrackerProfile oldp,
LQTrackerProfile newp) {
Toast.makeText(arg0, "onTrackerProfileChanged ",Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pop.geoloqi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<permission
android:name="com.pop.geoloqi.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.pop.geoloqi.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".GeoloqiExampleActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.geoloqi.android.sdk.service.LQService"
android:exported="false" />
<receiver
android:name=".GeoReceiver"
android:enabled="false"
android:exported="false" >
<intent-filter>
<action android:name="com.geoloqi.android.sdk.action.LOCATION_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="com.geoloqi.android.sdk.receiver.LQDeviceMessagingReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.pop.geoloqi" />
</intent-filter>
</receiver>
</application>
</manifest>
There was a bug in earlier versions of the Geoloqi Android SDK. If you update to the latest version this problem should be resolved.

Categories

Resources