SpeechRecognizer insufficient permissions error with Glass - android

I am building an application with the GDK sneak peek and am having trouble getting speech recognition working in an immersive app. This is my first android project.
I tried to follow this: How can I use speech recognition without the annoying dialog in android phones
After making initial progress, I hit a problem where the RecognitionListener class is throwing Error 9, insufficient permissions.
I am using the GDK, which is Android-15.
Initialization of the Recognizer is in my onCreate() method:
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
When I receiver a tap callback, I start listening:
private GestureDetector createGestureDetector(Context context) {
GestureDetector gestureDetector = new GestureDetector(context);
//Create a base listener for generic gestures
gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
#Override
public boolean onGesture(Gesture gesture) {
// Log.info(gesture.name());
if (gesture == Gesture.TAP) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
return true;
}
return false;
}
});
return gestureDetector;
}
And here is the definition of my listener class:
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
// mText.setText("error " + error);
}
public void onResults(Bundle results)
{
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
// mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.medicalglass"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.medicalglass.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Immediately after the touch event comes in and I call start listening, the listener's onError method is called with error code 9, which denotes insufficient permissions. If anyone has any experience with android speech commands, or glass speech commands and know why this continues to fail I would be very appreciative. Thanks.

You have to request for permission on Android M onward.
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED)
return;
else {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(activity, "Record audio is required", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO);
}
}

Start by changing this code:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
To this code:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getApplication().getPackageName());
speechRecognizer.startListening(intent);
EDIT:
Add this to your manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
If you have an error please past your LogCat.

This should be working now with API Level 19 and the two permissions mentioned above.

Voice recognition not available offline (yet?), see this Google Glass requested feature for allowing offline voice recognition (Issue 305)

In my situation (SpeechRecognizer permissions that used to be sufficient in API 8, no longer sufficient in API 29), I solved the problem by going to Settings > Permissions > Permissions > Microphone > Slide (from OFF to ON) for my app:

Related

isGestureDetectionAvailable() always returning False

I am trying to detect gestures on a fingerprint scanner. I have made an Accessibility service and yet I get back "False" for this method isGestureDetectionAvailable(). However, my device is capable of detecting the gestures.
I have applied everything according to the code mentioned on the official Android developer website.
This is my Android Manifest Code.
<application
.....>
<service
android:name=".AccessibilityService"
android:enabled="true"
android:exported="true"
android:label="My application"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action
android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/my_gesture_service" />
</service>
This is my Service.
public class AccessibilityService extends
android.accessibilityservice.AccessibilityService {
private static final String TAG =
AccessibilityService.class.getSimpleName();
#Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
Log.d("ACCEVENT", accessibilityEvent.toString());
}
#Override
public void onInterrupt() {
Log.d("ACCEVENT", "onAccessibilityEvent Inturupt");
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
FingerprintGestureController gestureController = getFingerprintGestureController();
Toast.makeText(getApplicationContext(), "Is available: " + gestureController.isGestureDetectionAvailable(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Is available: " + gestureController.isGestureDetectionAvailable() );
FingerprintGestureController.FingerprintGestureCallback callback = new
FingerprintGestureController.FingerprintGestureCallback() {
#Override
public void onGestureDetectionAvailabilityChanged(boolean available) {
super.onGestureDetectionAvailabilityChanged(available);
Toast.makeText(getApplicationContext(), "Gesture available change to: " + available, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onGestureDetectionAvailabilityChanged " + available);
}
#Override
public void onGestureDetected(int gesture) {
super.onGestureDetected(gesture);
Toast.makeText(getApplicationContext(), "Gesture: " + gesture, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onGestureDetected " + gesture);
}
};
gestureController.registerFingerprintGestureCallback(callback, null);
}
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind " );
return super.onUnbind(intent);
}
}
This is my XML code for the service
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault|flagRequestFingerprintGestures"
android:canRequestFingerprintGestures="true" />
How do you know that your device supports gestures? Does TalkBack work with them? Otherwise, it's possible that the hardware vendor didn't report that the hardware detects gestures.

Fingerprint gesture availability always false for android 9

I'm trying to use fingerprint gestures in an accessibility service. It is working fine in android 8.1 devices (Nexus 5x emulator, Moto G5s Plus) but not working in android 9 devices (Nexus 5x emulator, Samsung M30s). I've added all the required lines mentioned in this question:
Android O - fingerprint gesture callback not working
Do I have to add something extra for android 9? Can someone please help me?
activity_service.xml:
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFeedbackType="feedbackGeneric"
android:canRequestFingerprintGestures="true"
android:accessibilityFlags="flagDefault|flagRequestFingerprintGestures"
android:canPerformGestures="true"/>
MyAccessibilityService.java:
public class MyAccessibilityService extends AccessibilityService {
private static final String TAG = MyAccessibilityService.class.getSimpleName();
#Override
public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
Log.d(TAG, "onAccessibilityEvent");
}
#Override
public void onInterrupt() {
Log.d(TAG, "onInterrupt");
}
#Override
protected boolean onGesture(int gestureId) {
Log.d(TAG, "onGesture " + gestureId);
return super.onGesture(gestureId);
}
#Override
protected boolean onKeyEvent(KeyEvent event) {
Log.d(TAG, "onKeyEvent " + event.getKeyCode());
return super.onKeyEvent(event);
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy" , Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
FingerprintGestureController gestureController = getFingerprintGestureController();
Toast.makeText(getApplicationContext(), "Is available: " + gestureController.isGestureDetectionAvailable(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Is available: " + gestureController.isGestureDetectionAvailable() );
FingerprintGestureController.FingerprintGestureCallback callback = new
FingerprintGestureController.FingerprintGestureCallback() {
#Override
public void onGestureDetectionAvailabilityChanged(boolean available) {
super.onGestureDetectionAvailabilityChanged(available);
Toast.makeText(getApplicationContext(), "Gesture available change to: " + available, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onGestureDetectionAvailabilityChanged " + available);
}
#Override
public void onGestureDetected(int gesture) {
super.onGestureDetected(gesture);
switch (gesture){
case GESTURE_SWIPE_DOWN:
CameraManager mCameraManager;
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String mCameraId = "";
try {
mCameraId = mCameraManager.getCameraIdList()[0];
mCameraManager.setTorchMode(mCameraId, true);
}
catch (Exception e){
}
break;
case GESTURE_SWIPE_UP:
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
mCameraManager.setTorchMode(mCameraId, false);
}
catch (Exception e){
}
break;
default:
Toast.makeText(getApplicationContext()
, "Gesture: " + gesture, Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "onGestureDetected " + gesture);
}
};
gestureController.registerFingerprintGestureCallback(callback, new Handler());
}
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind " );
return super.onUnbind(intent);
}}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.bignerdranch.com.myapplication">
<uses-feature android:name="android.hardware.fingerprint"/>
<uses-feature android:name="android.hardware.camera.flash" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission." />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal" />
<application>
<service
android:name=".MyAccessibilityService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/activity_service" />
</service>
</application>
</manifest>
You need to add this line in the gesture service xml
android:accessibilityFlags="flagDefault|flagRequestFingerprintGestures"
It could also be device related. Check the following answer for information.
Android M FingerprintManager.isHardwareDetected() returns false on a Samsung Galaxy S5
Can you provide your code samples for further debugging if this doesn't work?

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

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.

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>

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

Categories

Resources