I'm trying to write a application that allows me to send messages from my android phone to the console on my PC. I already have code to use sockets to send messages from one PC to another. Right now I am trying to implement the Wifi-Direct on the android phone by following this tutorial:
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
I have 2 java files:
MainActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity{
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d("Peers Discovered", "SUCCEEDED");
}
#Override
public void onFailure(int reasonCode) {
Log.d("Peers Discovered", "FAILURE");
}
});
}
/* register the broadcast receiver with the intent values to be matched */
#Override
protected void onResume(){
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause(){
super.onPause();
unregisterReceiver(mReceiver);
}
}
WifiDirectBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.widget.Toast;
/**
* A BroadcastReceiver that notifies of important Wi-Fi p2p events.
*/
class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
WifiP2pManager.PeerListListener myPeerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
for (WifiP2pDevice d: wifiP2pDeviceList.getDeviceList()){
Log.d("WIFIP2PDEVICE", "Device d's address: " + d.deviceAddress);
if (d.deviceAddress==""){
//obtain a peer from the WifiP2pDeviceList
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
//success logic
}
#Override
public void onFailure(int reason) {
//failure logic
}
});
}
}
}
};
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi P2P is enabled
Toast.makeText(context, "Wi-Fi Direct is enabled", Toast.LENGTH_SHORT).show();
} else {
// Wi-Fi P2P is not enabled
Toast.makeText(context,"Wifi is disabled, please enable to continue", Toast.LENGTH_SHORT);
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Call WifiP2pManager.requestPeers() to get a list of current peers
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
mManager.onPeersAvailable(myPeerListListener); //ERROR HAPPENS HERE
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
The issue I currently have is that I am getting the error:
Cannot resolve method 'onPeersAvailable(android.net.wifi.p2p.WifiP2pManager.PeerListListener)
Why doesn't my code recognise the implementation of onPeersAvailable(...)?
You are trying to call onPeersAvailable(myPeerListListener) directly. That is not how it works (and if you look back into the tutorial you followed, you'll see they are not doing it either). All you need to do is:
register the listener callback with the WifiP2pManager
the manager will then call your listener whenever it is ready (asynchronously)
Remove the offending line, and things should be fine.
Related
I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.
I am trying to update a ProgressBar from a Service task. I implemented a BroadcastReceiver so that I can interact with the UI thread. I update the ProgressBar in the main activity, and receive the data from the MyService activity. The MyService activity executes an Async task and updates the intent that should be sent back in the OnProgressUpdate method.
Here is my code:
MainActivity:
package com.example.services;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.ProgressBar;
import static android.content.Intent.ACTION_ATTACH_DATA;
public class MainActivity extends AppCompatActivity {
private MyBroadRequestReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(ACTION_ATTACH_DATA);
receiver = new MyBroadRequestReceiver();
registerReceiver( receiver, filter);
}
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
//pb.setProgress();
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
public class MyBroadRequestReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
int progress = intent.getFlags();
pb.setProgress(progress);
}
}
}
MyService:
package com.example.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
int counter = 0;
static final int UPDATE_INTERVAL = 1000;
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
doSomethingRepeatedly();
try {
new DoBackgroundTask().execute(
new URL("http://www.amazon.com/somefiles.pdf"),
new URL("http://www.wrox.com/somefiles.pdf"),
new URL("http://www.google.com/somefiles.pdf"),
new URL("http://www.learn2develop.net/somefiles.pdf"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null){
timer.cancel();
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.d("MyService", String.valueOf(++counter));
}
}, 0, UPDATE_INTERVAL);
}
private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalBytesDownloaded = 0;
for (int i = 0; i < count; i++) {
totalBytesDownloaded += DownloadFile(urls[i]);
//Intent broadcastIntent = new Intent();
//broadcastIntent.setAction(Intent.ACTION_ATTACH_DATA);
//sendBroadcast(broadcastIntent);
publishProgress((int) (((i + 1) / (float) count) * 100));
}
return totalBytesDownloaded;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("Downloading files", String.valueOf(progress[0]) + "% downloaded");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.example.services.MainActivity");
//broadcastIntent.putExtra("progress",progress);
broadcastIntent.setFlags(progress[0]);
sendBroadcast(broadcastIntent);
Toast.makeText(getBaseContext(),
String.valueOf(progress[0]) + "% downloaded-"+counter,
Toast.LENGTH_LONG).show();
}
protected void onPostExecute(Long result) {
Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes",
Toast.LENGTH_LONG).show();
//stopSelf();
}
}
private int DownloadFile(URL url) {
try {
//---simulate taking some time to download a file---
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//---return an arbitrary number representing
// the size of the file downloaded---
return 100;
}
}
Please take a look at my onProgressUpdate and tell me if I am doing this correclty. My ProgressBar is not being updated at all.
Because you don't startService ononCreate() Method. Service will not run.
Firs of all this is not good solution to the problem your solving. Please go through Google Android docs Backgournd guide
I suggest you should switch to DownloadManager.
Your intent filter is defining to "ACTION_ATTACH_DATA"
IntentFilter filter = new IntentFilter(ACTION_ATTACH_DATA);
So, send your broadcast like this:
Intent i = new Intent(ACTION_ATTACH_DATA);
sendBroadcast(i);
Also, don't forget to unregister the broadcast at onDestroy
I am trying to use Google's Nearby Messages API for the first time. I downloaded some source code from GitHub and tried to compile it using Android Studio. There is an import that Android Studio cannot resolve:
import com.google.android.gms.nearby.messages.SubscribeOptions;
My Gradle file defines the following dependencies:
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.google.android.gms:play-services:7.8.0'
compile 'com.google.android.gms:play-services-nearby:7.8.0'
and this is the Activity in which I am using the aforementioned library:
package com.example.android.nearbybeacons;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.messages.Message;
import com.google.android.gms.nearby.messages.MessageListener;
import com.google.android.gms.nearby.messages.Strategy;
import com.google.android.gms.nearby.messages.SubscribeOptions;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG =
MainActivity.class.getSimpleName();
private static final int REQUEST_RESOLVE_ERROR = 100;
private static final int REQUEST_PERMISSION = 42;
private GoogleApiClient mGoogleApiClient;
private ArrayAdapter<OfferBeacon> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.list);
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
list.setAdapter(mAdapter);
list.setOnItemClickListener(this);
//Construct a connection to Play Services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Nearby.MESSAGES_API)
.build();
//When launching from a notification link
if (BeaconService.ACTION_DISMISS.equals(getIntent().getAction())) {
//Fire a clear action to the service
Intent intent = new Intent(this, BeaconService.class);
intent.setAction(BeaconService.ACTION_DISMISS);
startService(intent);
}
}
#Override
protected void onStart() {
super.onStart();
//Initiate connection to Play Services
mGoogleApiClient.connect();
//The location permission is required on API 23+ to obtain BLE scan results
int result = ActivityCompat
.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (result != PackageManager.PERMISSION_GRANTED) {
//Ask for the location permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSION);
}
}
#Override
protected void onStop() {
super.onStop();
//Tear down Play Services connection
if (mGoogleApiClient.isConnected()) {
Log.d(TAG, "Un-subscribing…");
Nearby.Messages.unsubscribe(
mGoogleApiClient,
mMessageListener);
mAdapter.clear();
mGoogleApiClient.disconnect();
}
}
// This is called in response to a button tap in the system permissions dialog.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_RESOLVE_ERROR) {
if (resultCode == RESULT_OK) {
// Permission granted or error resolved successfully then we proceed
// with publish and subscribe..
subscribe();
} else {
// This may mean that user had rejected to grant nearby permission.
showToast("Failed to resolve error with code " + resultCode);
}
}
if (requestCode == REQUEST_PERMISSION) {
if (resultCode != RESULT_OK) {
showToast("We need location permission to get scan results!");
finish();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OfferBeacon item = mAdapter.getItem(position);
showToast(item.offer);
}
/* Nearby Messages Callbacks */
//NOTE: These callbacks are NOT triggered on the main thread!
private MessageListener mMessageListener = new MessageListener() {
// Called each time a new message is discovered nearby.
#Override
public void onFound(Message message) {
Log.i(TAG, "Found message: " + message);
final OfferBeacon beacon = new OfferBeacon(message);
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.add(beacon);
}
});
}
// Called when the publisher (beacon) is no longer nearby.
#Override
public void onLost(Message message) {
Log.i(TAG, "Lost message: " + message);
final OfferBeacon beacon = new OfferBeacon(message);
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.remove(beacon);
}
});
}
};
/* API Client Callbacks */
#Override
public void onConnected(Bundle bundle) {
//Once connected, we have to check that the user has opted in
Runnable runOnSuccess = new Runnable() {
#Override
public void run() {
//Subscribe once user permission is verified
subscribe();
}
};
ResultCallback<Status> callback =
new ErrorCheckingCallback(runOnSuccess);
Nearby.Messages.getPermissionStatus(mGoogleApiClient)
.setResultCallback(callback);
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "OnConnectionSuspended");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.w(TAG, "OnConnectionFailed");
}
private void subscribe() {
Log.d(TAG, "Subscribing…");
SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.build();
//Active subscription for foreground messages
Nearby.Messages.subscribe(mGoogleApiClient,
mMessageListener, options);
//Passive subscription for background messages
Intent serviceIntent = new Intent(this, BeaconService.class);
PendingIntent trigger = PendingIntent.getService(this, 0,
serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
ResultCallback<Status> callback = new BackgroundRegisterCallback();
Nearby.Messages.subscribe(mGoogleApiClient, trigger, options)
.setResultCallback(callback);
}
private class BackgroundRegisterCallback implements ResultCallback<Status> {
#Override
public void onResult(#NonNull Status status) {
//Validate if we were able to register for background scans
if (status.isSuccess()) {
Log.d(TAG, "Background Register Success!");
} else {
Log.w(TAG, "Background Register Error ("
+ status.getStatusCode() + "): "
+ status.getStatusMessage());
}
}
}
//ResultCallback triggered when to handle Nearby permissions check
private class ErrorCheckingCallback implements ResultCallback<Status> {
private final Runnable runOnSuccess;
private ErrorCheckingCallback(#Nullable Runnable runOnSuccess) {
this.runOnSuccess = runOnSuccess;
}
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Permission status succeeded.");
if (runOnSuccess != null) {
runOnSuccess.run();
}
} else {
// Currently, the only resolvable error is that the device is not opted
// in to Nearby. Starting the resolution displays an opt-in dialog.
if (status.hasResolution()) {
try {
status.startResolutionForResult(MainActivity.this,
REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
showToastAndLog(Log.ERROR, "Request failed with exception: " + e);
}
} else {
showToastAndLog(Log.ERROR, "Request failed with : " + status);
}
}
}
}
private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private void showToastAndLog(int logLevel, String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
Log.println(logLevel, TAG, message);
}
}
Can anyone tell me what I'm doing wrong?
My guess is that you will be able to resolve this by updating the Play Services version you are using from v7.8.0 to v8.4.0 (the latest version as of this answer date). The Nearby APIs were introduced in v7.8.0, at which time subscription could be accomplished using a method signature of the form
subscribe(GoogleApiClient, MessageListener, Strategy)
However, this method is now (in v8.4.0) marked as deprecated, and a new method with the following signature is recommended in its place:
subscribe (GoogleApiClient, MessageListener, SubscribeOptions)
Based on this information it seems fairly likely that the SubscribeOptions type was introduced whenever the previously-described deprecation took place, which was clearly post-v7.8.0.
See these docs for reference.
Issue : speak failed:not bound to tts engine
I am implementing textToSpeech functionality. I am getting the exception as speak failed: not bound to tts engine. I am implementing the async task with it. the async task will be reading the mail. And i want to convert the mail body to speech.
package com.example.trynot;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Locale;
import com.example.trynot.MainActivity.ReadMailSample;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Notify extends Activity implements TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
public Notify()
{
System.out.println("Inside Constructor");
speakOut();
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
System.out.println("inside INIT");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
System.out.println("inside SPeak out");
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
}
}
You should move instatiation of tts engine instance to onCreate, this line:
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
change to:
public TextToSpeech tts;
and add inside your onCreate:
tts = new TextToSpeech(MainActivity.c, Notify.this);
And - whats most important - do not use constructor in Activity derived classes:
public Notify()
{
System.out.println("Inside Constructor");
speakOut();
}
should be your onCreate:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//speakOut(); // here tts is not yet initialized, call it in onInit on success
//tts = new TextToSpeech(MainActivity.c, Notify.this); // whats MainActivity.c?
tts = new TextToSpeech(this, this);
}
your google text to speech engine may be disable... once check it on your setting
if it is disable it also shows the same error
When I sign in through Google Sign-In to ActivityA, I want ActivityB to sign in to the same account simultaneously and and have all the capabilities of ActivityA. When I sign-out of ActivityB, I want it to also sign out of ActivityA.
For example, I have a HomeActivity using Google's PlusApi and then I have a MapsActivity that will be used for my navigation and all other Api Services I want to include.
1) Is this possible?
2) Is this the best way to do this and/or is there a better way to do it?
Here is my Code:
HomeActivity
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
public class HomeActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Keys for persisting instance variables in savedInstanceState */
private static final String KEY_IS_RESOLVING = "is_resolving";
private static final String KEY_SHOULD_RESOLVE = "should_resolve";
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* View to display current status (signed-in, signed-out, disconnected, etc) */
private TextView mStatus;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
private static final String TAG = "SignInActivity";
//
// private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Restore from saved instance state
// [START restore_saved_instance_state]
if (savedInstanceState != null) {
mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING);
mShouldResolve = savedInstanceState.getBoolean(KEY_SHOULD_RESOLVE);
}
// [END restore_saved_instance_state]
// Set up button click listeners
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
// spinner = (ProgressBar)findViewById(R.id.sign_in_loading);
// spinner.setVisibility(View.VISIBLE);
// Log.w(TAG, "Spinner is visible");
//
//
// findViewById(R.id.login_screen).setVisibility(View.INVISIBLE);
// Large sign-in
((SignInButton) findViewById(R.id.sign_in_button)).setSize(SignInButton.SIZE_WIDE);
// Start with sign-in button disabled until sign-in either succeeds or fails
findViewById(R.id.sign_in_button).setEnabled(false);
// Set up view instances
mStatus = (TextView) findViewById(R.id.status);
// Build GoogleApiClient to request access to the basic user profile
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.build();
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
// Show signed-in user's name
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
if (currentPerson != null) {
String name = currentPerson.getDisplayName();
mStatus.setText(getString(R.string.signed_in_fmt, name));
} else {
Log.w(TAG, getString(R.string.error_null_person));
mStatus.setText(getString(R.string.signed_in_err));
}
// Set button visibility
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
Log.w(TAG, "UI has been updated.");
} else {
// Show signed-out message
mStatus.setText(R.string.signed_out);
// Set button visibility
findViewById(R.id.sign_in_button).setEnabled(true);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
#Override
public void onConnected(Bundle bundle) {
// onConnected indicates that an account was selected on the device, that the selected
// account has granted any requested permissions to our app and that we were able to
// establish a service connection to Google Play services.
Log.d(TAG, "onConnected:" + bundle);
// Show the signed-in UI
updateUI(true);
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost. The GoogleApiClient will automatically
// attempt to re-connect. Any UI elements that depend on connection to Google APIs should
// be hidden or disabled until onConnected is called again.
Log.w(TAG, "onConnectionSuspended:" + i);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mStatus.setText(R.string.signing_in);
// [START sign_in_clicked]
mShouldResolve = true;
mGoogleApiClient.connect();
// [END sign_in_clicked]
break;
case R.id.sign_out_button:
// Clear the default account so that GoogleApiClient will not automatically
// connect in the future.
// [START sign_out_clicked]
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
// [END sign_out_clicked]
updateUI(false);
break;
case R.id.disconnect_button:
// Revoke all granted permissions and clear the default account. The user will have
// to pass the consent screen to sign in again.
// [START disconnect_clicked]
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
// [END disconnect_clicked]
updateUI(false);
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
} else {
// Could not resolve the connection result, show the user an
// error dialog.
showErrorDialog(connectionResult);
}
} else {
// Show the signed-out UI
updateUI(false);
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
Intent startMaps = new Intent(HomeActivity.this, MapsActivity.class);
HomeActivity.this.startActivity(startMaps);
}
}
private void showErrorDialog(ConnectionResult connectionResult) {
int errorCode = connectionResult.getErrorCode();
if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
// Show the default Google Play services error dialog which may still start an intent
// on our behalf if the user can resolve the issue.
GooglePlayServicesUtil.getErrorDialog(errorCode, this, RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mShouldResolve = false;
updateUI(false);
}
}).show();
} else {
// No default Google Play Services error, display a message to the user.
String errorString = getString(R.string.play_services_error_fmt, errorCode);
Toast.makeText(this, errorString, Toast.LENGTH_SHORT).show();
mShouldResolve = false;
updateUI(false);
}
}
}
MapsActivity
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.plus.Plus;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
View.OnClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
private HomeActivity mHomeActivity = new HomeActivity();
public static final String TAG = MapsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10*1000) //10 seconds, in milliseconds
.setFastestInterval(1 * 1000); //1 second, in milliseconds
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
}
#Override
public void onMapReady(GoogleMap map){
//Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.setMyLocationEnabled(true);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latlng = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location==null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
//Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_out_button:
// Clear the default account so that GoogleApiClient will not automatically
// connect in the future.
// [START sign_out_clicked]
// if (mGoogleApiClient.isConnected()) {
// Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
// mGoogleApiClient.disconnect();
// }
// [END sign_out_clicked]
Intent startHomeDisconnect = new Intent(MapsActivity.this, HomeActivity.class);
MapsActivity.this.startActivity(startHomeDisconnect);
break;
case R.id.disconnect_button:
// Revoke all granted permissions and clear the default account. The user will have
// to pass the consent screen to sign in again.
// [START disconnect_clicked]
// if (mGoogleApiClient.isConnected()) {
// Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
// Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
// mGoogleApiClient.disconnect();
// }
// [END disconnect_clicked]
Intent startHomeSignOut = new Intent(MapsActivity.this, HomeActivity.class);
MapsActivity.this.startActivity(startHomeSignOut);
break;
}
}
}