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.
Related
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>
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.
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.
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.
I faced with the problem - Google map is not shown in my Android Application. The App is based on O'Reilly Android Task manager Application.
Here is my layout
<com.google.android.maps.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
class="com.google.android.gms.maps.MapFragment"
android:clickable="true"
android:apiKey="AIzaSyALl1yI4zMyjnHoTSkgQjKQLE78uWZcAYk"
android:layout_below="#id/map_location_button"
android:layout_above="#+id/use_this_location_button"/>
my Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.khalilov.android.taskmanager"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.khalilov.android.taskmanager.permission.MAPS_RECEIVE"
android:protectionLevel="signature"></permission>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:name=".TaskManagerApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ViewTasksActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddTaskActivity" android:text="#string/app_name" />
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".AddLocationMapActivity"
android:text="#string/add_location_to_task" />
<meta-data
android:name="com.google.android.v2.API_KEY"
android:value="AIzaSyALl1yI4zMyjnHoTSkgQjKQLE78uWZcAYk"/>
<service android:name=".services.MyService"/>
</application>
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="24" />
</manifest>
And Java code
public class AddLocationMapActivity extends MapActivity {
public static final String ADDRESS_RESULT = "address";
private EditText addressText;
private Button mapLocationButton;
private Button useLocationButton;
private MapView mapView;
private Address address;
private MyLocationOverlay myLocationOverlay;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.add_location);
setUpView();
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
}
protected void mapCurrentAddress() {
//getting address from input
String addressString = addressText.getText().toString();
//geocoder - search for address to find a location
Geocoder g = new Geocoder(this);
List<Address> addresses;
try {
addresses = g.getFromLocationName(addressString, 1);
if(null != addresses && addresses.size()>0) {
address = addresses.get(0);
List<Overlay> mapOverlays = mapView.getOverlays();
AddressOverlay addressOverlay = new AddressOverlay(address);
mapOverlays.add(addressOverlay);
mapOverlays.add(myLocationOverlay);
mapView.invalidate();
final MapController mapController = mapView.getController();
mapController.animateTo(addressOverlay.getGeopoint(), new
Runnable() {
public void run() {
mapController.setZoom(12);
}
});
useLocationButton.setEnabled(true);
} else {
//Tell the user no results for that address
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setUpView() {
addressText = (EditText)findViewById(R.id.task_address);
mapLocationButton = (Button)findViewById(R.id.map_location_button);
useLocationButton = (Button)findViewById(R.id.use_this_location_button);
mapView = (MapView)findViewById(R.id.map);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
mapView.invalidate();
useLocationButton.setEnabled(false);
mapView.setBuiltInZoomControls(true);
mapLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mapCurrentAddress();
}
});
useLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (null != address) {
Intent intent = new Intent();
intent.putExtra(ADDRESS_RESULT, address);
setResult(RESULT_OK, intent);
}finish();
}
});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
//location of device
protected boolean isLocationDisplayed() {
return true;
}
}
log
It would be great if you help me to find the solution. Thanks