textRecognizer.isOperational() return false - java

i run the app in emulator it works but run it in phone api 17 and api 22 textRecognizer.isOperational() return false
what is the problem?
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.CAMERA"/>
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="ocr"/>
</application>
MainActivity
public class MainActivity extends AppCompatActivity {
SurfaceView CameraView;
TextView textView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraView = (SurfaceView) findViewById(R.id.surface_view);
textView = (TextView) findViewById(R.id.textview);
final TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
if (!textRecognizer.isOperational()) {
Log.w("MainActivity", "dependencies are not available");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
CameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
return;
}
try {
cameraSource.start(CameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> item = detections.getDetectedItems();
if(item.size() != 0){
textView.post(new Runnable() {
#Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for (int i=0;i<item.size();i++){
TextBlock items = item.valueAt(i);
stringBuilder.append(items.getValue());
stringBuilder.append("\n");
}
textView.setText(stringBuilder.toString());
}
});
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(CameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
please help thanks
emulator api 25
phone huawei g730 u10 api 17
Imet api 22
Everytime I launch the apk, "Text recognizer could not be set up : is displayed. Even though I have set all dependencies but still i am getting this error. Please help why TextRecognizer.isOperational() is always false.

Related

After pressing record button recording starts and instantly stops in Android App

I am making my first Android App where I need to take a video of 45 secs to calculate pulse from it.
Recording video is coded the simple way, using startActivityForResult()(something similar to record video using intent). The activity to record video successfully starts but when the record button is pressed recording starts and instantly stops. I have no clue as to why. Logcat displays no error output with respect to the activity. Even, there is no mention of any of my source files in any info or error Logs in Logcat.
Here are my files
MainActivity.java
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private Camera c;
private CameraView cv1;
private FrameLayout view_camera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))) {
this.finish();
System.exit(0);
}
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture video_capture;
Button button_symptoms = (Button)findViewById(R.id.button_symptoms);
Button button_upload_signs = (Button)findViewById(R.id.button_upload_signs);
Button button_measure_heart_rate = (Button)findViewById(R.id.button_measure_heart_rate);
Button button_measure_respiratory_rate = (Button)findViewById(R.id.button_measure_respiratory_rate);
cv1 = new CameraView(getApplicationContext(), this);
view_camera = (FrameLayout)findViewById(R.id.view_camera);
view_camera.addView(cv1);
TextView finger_on_sensor = (TextView)findViewById(R.id.text_finger_on_sensor);
finger_on_sensor.setVisibility(View.INVISIBLE);
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg_view, MotionEvent arg_me) {
finger_on_sensor.setVisibility(View.INVISIBLE);
File file_video = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/video_finger.mp4");
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
List<ResolveInfo> resInfoList = getApplicationContext().getPackageManager().queryIntentActivities(intent_record_video, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
getApplicationContext().grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
return false;
}
});
button_symptoms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
Intent intent = new Intent(getApplicationContext(), Loggin_symptoms.class);
startActivity(intent);
}
});
button_upload_signs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
}
});
button_measure_heart_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
finger_on_sensor.setVisibility(View.VISIBLE);
}
});
button_measure_respiratory_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
SensorManager manager_sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_accelerometer = manager_sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
manager_sensor.registerListener(MainActivity.this, sensor_accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
});
}
public void setCam(Camera arg_camera) {
c = arg_camera;
}
#Override
public void onSensorChanged(SensorEvent arg_event) {
float x = arg_event.values[0];
float y = arg_event.values[1];
float z = arg_event.values[2];
Log.i("ACCELEROMETER", String.valueOf(x) + ' ' + String.valueOf(y) + ' ' + String.valueOf(z));
}
#Override
public void onAccuracyChanged(Sensor arg_sensor, int arg_accuracy) {
}
public Camera getcam() {
Camera c = null;
try { c = Camera.open(0); }
catch (Exception e) {
}
return c;
}
#Override
protected void onPause() {
super.onPause();
c.unlock();
// if (c != null) {
// c.stopPreview();
// c.release();
// c = null;
// }
}
#Override
protected void onResume() {
super.onResume();
// if (c != null) {
// c.stopPreview();
// c.release();
// c = null;
// }
// cv1 = new CameraView(getApplicationContext(), this);
// view_camera.addView(cv1);
}
#Override
protected void onDestroy() {
if (c != null) {
c.stopPreview();
c.release();
c = null;
}
super.onDestroy();
}
}
CameraView.java
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder_surface;
private Camera camera_selected;
MainActivity act1;
public CameraView(Context arg_context, MainActivity arg_activity) {
super(arg_context);
// camera_selected = arg_camera;
act1 = arg_activity;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
holder_surface = getHolder();
holder_surface.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
holder_surface.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder arg_holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
// Log.i("CAMNULL", "CAM IS : " + String.valueOf(camera_selected == null));
Camera c = null;
try {
c = Camera.open(0);
} catch (Exception e) {
Log.e("CAMERA", "Camera not opened");
}
act1.setCam(c);
camera_selected = c;
camera_selected.setPreviewDisplay(arg_holder);
// camera_selected.startPreview();
// Log.i("Cam", "surface creator");
} catch (IOException e) {
// Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
// if (camera_selected != null) {
// camera_selected.stopPreview();
// camera_selected.release();
// camera_selected = null;
// }
}
public void surfaceChanged(SurfaceHolder arg_holder, int arg_format, int arg_width, int arg_height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder_surface.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera_selected.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
camera_selected.setPreviewDisplay(holder_surface);
camera_selected.startPreview();
} catch (Exception e){
// Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cse535a1">
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:requestLegacyExternalStorage="true"
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/Theme.CSE535A1">
<activity android:name=".Loggin_symptoms"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.cse535a1.provider"
android:exported="false"
android:grantUriPermissions="true">
<!-- ressource file to create -->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
</application>
</manifest>
I am attaching images for you convenience.
Activity started and record button is pressed (i want to record a video for 45 secs).
The next instant recording stops
File file_video = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/video_finger.mp4");
final int VIDEO_CAPTURE = 1;
// StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
// StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
// List<ResolveInfo> resInfoList = getApplicationContext().getPackageManager().queryIntentActivities(intent_record_video, PackageManager.MATCH_DEFAULT_ONLY);
// for (ResolveInfo resolveInfo : resInfoList) {
// String packageName = resolveInfo.activityInfo.packageName;
// getApplicationContext().grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
// }
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
This code(in my MainActivity.java file) is similar to videobasics on Android Developers. With my experience, I will say that it will work for API level 28 and not for API level 30, don't know about API 29.

startService() and stopService() not working properly

The problem I'm currently experiencing is that I am unable to start and stop the service of another class. I was able to run the application but I couldn't get the results I wanted, as the program didn't show any errors. I thought it was something wrong with my buttons at first, so i tried using System.out.println to see if i get any feedback, in which i did. Then, i decided to try it on my other class (location.java), the System.out.Println I used did not work, which probably means its not even working.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText input;
private Button start, stop;
private Intent intent;
public static int minute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iniUI();
}
private void iniUI() {
input=findViewById(R.id.input);
start=findViewById(R.id.start);
stop=findViewById(R.id.stop);
start.setEnabled(false);
stop.setEnabled(false);
start.setOnClickListener(this);
stop.setOnClickListener(this);
intent=new Intent(this, Location.class);
permission();
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.start) {
minute=Integer.parseInt(input.getText().toString());
startTracking();
}
else if(view.getId()==R.id.stop)
stopTracking();
}
private void permission(){
if(ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED) {
start.setEnabled(true);
}
else{
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==0){
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
permission();
}
}
}
private void startTracking(){
startService(intent);
buttonAlt();
}
private void stopTracking() {
stopService(intent);
buttonAlt();
}
private void buttonAlt(){
start.setEnabled(!start.isEnabled());
stop.setEnabled(!start.isEnabled());
}}
Location.java
public class Location extends Service{ private Thread thread;
private LocationManager locationManager;
private double longitude, latitude;
private String dateTime, encodeData;
public Location() {
}
#Override
public void onCreate() {
super.onCreate();
thread = new Thread(runThread);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
thread.start();
return super.onStartCommand(intent, flags, startId);
}
private Runnable runThread = new Runnable() {
#Override
public void run() {
while (true) {
try {
System.out.println("Shutting down");
long sMinutes = MainActivity.minute * 60 * 1000;
Thread.sleep(sMinutes);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("Running");
sendLocation();
}
}
};
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
private void sendLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
#SuppressLint("MissingPermission")
android.location.Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude=location.getLongitude();
latitude=location.getLatitude();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date(System.currentTimeMillis());
dateTime=sdf.format(date);
postData();
}
private void encodeData() throws UnsupportedEncodingException {
encodeData= URLEncoder.encode("datetime", "UTF-8") + "=" + URLEncoder.encode(dateTime, "UTF-8") +
"&" + URLEncoder.encode("latitude", "UTF-8") + "=" + URLEncoder.encode(Double.toString(latitude), "UTF-8") +
"&" + URLEncoder.encode("longitude", "UTF-8") + "=" + URLEncoder.encode(Double.toString(longitude), "UTF-8");
System.out.println("Lat:"+latitude);
System.out.println("Long:"+longitude);
}
private void postData(){
try {
encodeData();
URL url=new URL("A PHP SCRIPT TO OBTAIN MY LATITUDE AND LONGITUDE");
URLConnection urlConnection=url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(encodeData);
outputStreamWriter.flush();
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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">
<activity android:name=".Location"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
To sum it all up, both classes showed no errors, but only the MainActivity.java was working. Is there anything i could change about it to get it to work? I think it has something to do with my startService() and stopService().
It seems like in your Manifest file you have registered your service Location.java as an activity, it should work once you change that to service
<service android:name=".Location" />
instead of
<activity android:name=".Location"></activity>

Service doesn't work with Oreo 8.1 - The Detector does not work, nor does the process in the background

My call detector app is running fine on all android version except 8 Oreo. I get a deadlock paradigm: My detector is not called, and when I close the application the system kills it, not leaving it in the background.
I have already read the documentation from cable to tail https://developer.android.com/about/versions/oreo/background, I already looked a lot in google, and here in stack over flow, but no solution applied to my case, because of the required "dangerous" permissions.
My case seems simple: I have a detector, a service and the main with a button. I want it when the user calls a certain number, my main open.
What is the right way to fix this issue?
manifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_PERMISSION" />
<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">
<service
android:name=".CallDetectionService"
android:enabled="true"
android:exported="false"/>
<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.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</activity>
</application>
CallDetectionService.java
public class CallDetectionService extends Service {
private CallDetector callDetector;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
callDetector = new CallDetector(this);
int r = super.onStartCommand(intent, flags, startId);
callDetector.start();
return r;
}
#Override
public void onDestroy() {
super.onDestroy();
callDetector.stop();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
CallDetector.java
public class CallDetector {
public static final String MY_PREF = "MY_PREF";
public static final String NUMBER_KEY = "NUMBER_KEY";
private SharedPreferences sharedPreferences;
public class OutgoingDetector extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String compare_num = "12345678";
if (number.equals(compare_num)) {
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
setResultData(null);
context.startActivity(i);
}
}
}
private Context ctx;
private OutgoingDetector outgoingDetector;
public CallDetector(Context ctx) {
this.ctx = ctx;
outgoingDetector = new OutgoingDetector();
}
public void start() {
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingDetector, intentFilter);
}
public void stop(){
ctx.unregisterReceiver(outgoingDetector);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
private boolean detecting = false;
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 0;
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG", "Permission is granted");
return true;
} else {
Log.v("TAG", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return false;
}
} else {
Log.v("TAG", "Permission is granted");
return true;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
/* button.setOnClickListener(this); */
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
}
}
String action = "START";
final Intent intent = new Intent(this, CallDetectionService.class);
intent.setAction(action);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(CallDetector.MY_PREF, MODE_PRIVATE);
String number = sharedPreferences.getString(CallDetector.NUMBER_KEY, "URA VISUAL");
textView.setText(number);
}
}
What am I doing so wrong? I've been looking for a solution for 4 days and I still have not found anything.

Android Wear device not detecting any Nodes (phones) DataApi

I have and android wear and android phone app. I'm trying to get them connect and ultimately send messages from the watch to the phone. On the watch though, Wearable.CapabilityApi.getCapability() returns no nodes
Here is the Wear MainActivity:
public class MainActivity extends WearableActivity {
public static final String TAG = "WatchApp";
public GoogleApiClient mApiClient;
public static final int CONNECTION_TIME_OUT_MS = 1000;
public static String nodeId;
private static final String AIR_LIFT_CAPABILITY = "airlift";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initApi();
final Button btnUp = (Button)findViewById(R.id.btnUp);
btnUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = "Preset";
//mAdapter.add( text );
//mAdapter.notifyDataSetChanged();
sendMessage( text );
Log.i("WatchApp", "btnUp Sent Preset");
}
});
Button btnDown = (Button)findViewById(R.id.btnDown);
btnDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = "AirOut";
//mAdapter.add( text );
//mAdapter.notifyDataSetChanged();
sendMessage(text );
Log.i("WatchApp", "btnUp Sent AirOut");
}
});
// Enables Always-on
setAmbientEnabled();
}
private void initApi() {
mApiClient = getGoogleApiClient(this);
setOrUpdateNotification();
Log.i("WatchApp", "initApi()");
}
private GoogleApiClient getGoogleApiClient(Context context) {
return new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
}
private void setOrUpdateNotification() {
new Thread(new Runnable() {
#Override
public void run() {
CapabilityApi.GetCapabilityResult result =
Wearable.CapabilityApi.getCapability(
mApiClient, AIR_LIFT_CAPABILITY,
CapabilityApi.FILTER_REACHABLE).await(1000, TimeUnit.MILLISECONDS);
updateFindMeCapability(result.getCapability());
CapabilityApi.CapabilityListener capabilityListener =
new CapabilityApi.CapabilityListener() {
#Override
public void onCapabilityChanged(CapabilityInfo capabilityInfo) {
updateFindMeCapability(capabilityInfo);
}
};
// Wearable.CapabilityApi.addCapabilityListener(mApiClient, capabilityListener, AIR_LIFT_CAPABILITY);
}
}).start();
}
private void updateFindMeCapability(CapabilityInfo capabilityInfo) {
if (capabilityInfo.getNodes() == null) return;
Set<Node> connectedNodes = capabilityInfo.getNodes();
if (connectedNodes.isEmpty()) {
Log.i(TAG,"No Nodes Found.");
} else {
for (Node node : connectedNodes) {
// we are only considering those nodes that are directly connected
if (node.isNearby()) {
Log.i(TAG,"FOUND NODE");
nodeId = node.getId();
}
}
}
}
private void sendMessage(final String MESSAGE) {
if (nodeId != null) {
new Thread(new Runnable() {
#Override
public void run() {
mApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
Wearable.MessageApi.sendMessage(mApiClient, nodeId, MESSAGE, null);
mApiClient.disconnect();
Log.i("WatchApp", "Message ("+MESSAGE+") sent");
}
}).start();
} else {
Log.i("WatchApp", "No Nodes to send message!");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mApiClient.disconnect();
mApiClient = null;
Log.i("WatchApp", "onDestroy()");
}
}
Wear AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.schoen.jonathan.airliftwatch">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.schoen.jonathan.airliftwatch.MainActivity"
android:label="#string/app_name">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Phone MainActivity:
public class MainActivity extends Activity {
boolean mBound = false;
public static final String TAG = "PhoneApp";
public ListenerService listener;
public GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button)findViewById(R.id.btnStart);
Button btnStop = (Button)findViewById(R.id.btnStop);
Log.i("PhoneApp", "onCreate() Receiver Registered ");
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("PhoneApp", "btnStart Receiver Registered");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("PhoneApp", "btnStop Receiver unRegistered");
}
});
registerListener();
}
public void registerListener() {
client = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
listener = new ListenerService();
Wearable.MessageApi.addListener(client ,listener);
Log.i("PhoneApp", "registerListener() Listener Registered ");
}
#Override
protected void onStart() {
super.onStart();
registerListener();
Log.i("PhoneApp", "onStart() Listener Registered ");
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerListener();
Log.i("PhoneApp", "onResume() Listener Registered ");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregister our receiver
if (client != null && listener != null)
Wearable.MessageApi.removeListener(client, listener);
client = null;
listener = null;
Log.i("PhoneApp", "onPause() Listener Unregistered ");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//unregister our receiver
if (client != null && listener != null)
Wearable.MessageApi.removeListener(client, listener);
client = null;
listener = null;
Log.i("PhoneApp", "onPause() Listener Unregistered ");
}
}
Phone Listener Service:
public class ListenerService extends WearableListenerService {
String nodeId;
#Override
public void onMessageReceived(MessageEvent messageEvent) {
nodeId = messageEvent.getSourceNodeId();
Log.i(MainActivity.TAG, messageEvent.getPath());
showToast(messageEvent.getPath());
String msg_for_me = messageEvent.getPath();
if (msg_for_me == "AirOut")
{
Log.i(MainActivity.TAG, "Air Out");
} else if (msg_for_me == "Preset")
{
Log.i(MainActivity.TAG, "Preset");
}
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Phone Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.schoen.jonathan.airliftwatch">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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">
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<service
android:name="com.schoen.jonathan.airliftwatch.ListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Phone wear.xml:
<resources>
<string-array name="android_wear_capabilities">
<item>airlift</item>
</string-array>
</resources>
Any ideas why I get null result for returned nodes? my phone and watch are currently paired and i get updates on my watch from my phone from things like facebook and emails.
As stated in this thread, NodeApi can be used on the device side.
NodeApi.GetConnectedNodesResult nodes =
Wearable.NodeApi.getConnectedNodes(mApiClient).await();
Then for each node within nodes, you can call getDisplayName().
Also, based from this link, use the same debug certificate for both the handheld and wearable app, otherwise the CapabilityAPI won't work.

Issue By Lastlocation

I write a program that determine my Location. I follow only the instructions from Google pages this and this.
When the program runs on my Galaxy note 4 (android 5.0.1), it gives me a popup to choose my account then I choose that but after that comes other empty popup and stays there, without to give me my location.
But when I click outside the popup, the popup goes and I see the map normally without my location.
I have only one class, this:
public class MainActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final String DIALOG_ERROR = "dialog_error";
private boolean mResolvingError= false;
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR,false);
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
};
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if(mResolvingError)
return;
else if(result.hasResolution()){
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (SendIntentException e) {
mGoogleApiClient.connect();
}
}
else{
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
#Override
public void onConnected(Bundle connectionHint) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
//mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
//mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
private void showErrorDialog(int errorCode) {
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR,errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getSupportFragmentManager(),"errordialog");
}
public void onDialogDismissed(){
mResolvingError =false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment{
public ErrorDialogFragment(){};
public Dialog onCreatDialog(Bundle savedInstanceState){
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog){
((MainActivity)getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
}
and my manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.secondmapapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAOybgKFHhY0M3Mv_b0RbjT6yrIQCMWDHs"/>
</application>
</manifest>
I think this section is wrong
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
and must be changed into
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
The problem is where you specifies the API Type.

Categories