Bug Des:
a variable mBindingSerivce in UserState.java has not cleared after fail start Accessibility Service
mBindingSerivce means a Accessibility Service set of being started
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
synchronized (mLock) {
if (mService != service) {
if (mService != null) {
mService.unlinkToDeath(this, 0);
}
mService = service;
try {
// start Accessibility Service
mService.linkToDeath(this, 0);
} catch (RemoteException re) {
// fail start Accessibility Service, will run binderDied()
Slog.e(LOG_TAG, "Failed registering death link");
binderDied();
// will directly return
return;
}
}
mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service);
UserState userState = mUserStateWeakReference.get();
if (userState == null) return;
userState.addServiceLocked(this);
mSystemSupport.onClientChangeLocked(false);
// Initialize the service on the main handler after we're done setting up for
// the new configuration (for example, initializing the input filter).
mMainHandler.sendMessage(obtainMessage(
AccessibilityServiceConnection::initializeService, this));
}
}
public void binderDied() {
synchronized (mLock) {
// It is possible that this service's package was force stopped during
// whose handling the death recipient is unlinked and still get a call
// on binderDied since the call was made before we unlink but was
// waiting on the lock we held during the force stop handling.
if (!isConnectedLocked()) {
return;
}
mWasConnectedAndDied = true;
UserState userState = mUserStateWeakReference.get();
if (userState != null) {
userState.serviceDisconnectedLocked(this);
}
resetLocked();
mSystemSupport.getMagnificationController().resetAllIfNeeded(mId);
mSystemSupport.onClientChangeLocked(false);
}
}
so when restart Service, the code will run. please see 1 comment.
private void updateServicesLocked(UserState userState) {
// ...
for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
ComponentName componentName = ComponentName.unflattenFromString(
installedService.getId());
AccessibilityServiceConnection service = componentNameToServiceMap.get(componentName);
// Ignore non-encryption-aware services until user is unlocked
if (!isUnlockingOrUnlocked && !installedService.isDirectBootAware()) {
Slog.d(LOG_TAG, "Ignoring non-encryption-aware service " + componentName);
continue;
}
// 1. will run return due to mBindingService have not cleared
if (userState.mBindingServices.contains(componentName)) {
continue;
}
if (userState.mEnabledServices.contains(componentName)
&& !mUiAutomationManager.suppressingAccessibilityServicesLocked()) {
if (service == null) {
service = new AccessibilityServiceConnection(userState, mContext, componentName,
installedService, sIdCounter++, mMainHandler, mLock, mSecurityPolicy,
this, mWindowManagerService, mGlobalActionPerformer);
} else if (userState.mBoundServices.contains(service)) {
continue;
}
service.bindLocked();
} else {
if (service != null) {
service.unbindLocked();
}
}
}
//...
}
this will cause forever can't successful start service expect to restart AccessibilityManagerService
Related
I have just started exploring google-play-services-turnbased APIs. Till now I have been successful in creating a match. But from the documentation I haven't been able to figure out how to player's score after he completes his turn.
This is my onClickStartMatch method.
public void onStartMatchClicked() {
Intent intent =
Games.TurnBasedMultiplayer.getSelectOpponentsIntent(mHelper.getApiClient(), 1, 7, true);
startActivityForResult(intent, RC_SELECT_PLAYERS);
}
This is my onActivityResult method in my main activity class.
if (request == RC_SELECT_PLAYERS) {
if (response != RESULT_OK) {
// user canceled
return;
}
// Get the invitee list.
final ArrayList<String> invitees =
data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
// Get auto-match criteria.
Bundle autoMatchCriteria = null;
int minAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
int maxAutoMatchPlayers = data.getIntExtra(
Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
if (minAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0);
} else {
autoMatchCriteria = null;
}
TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setAutoMatchCriteria(autoMatchCriteria)
.build();
// Create and start the match.
Games.TurnBasedMultiplayer
.createMatch(mHelper.getApiClient(), tbmc)
.setResultCallback(new MatchInitiatedCallback());
}
This is my MatchInitiatedCallback class
public class MatchInitiatedCallback implements
ResultCallback<TurnBasedMultiplayer.InitiateMatchResult>,OnTurnBasedMatchUpdateReceivedListener {
#Override
public void onResult(TurnBasedMultiplayer.InitiateMatchResult result) {
// Check if the status code is not success.
Status status = result.getStatus();
if (status.isSuccess()) {
Log.d("turnbased","Turn Based Match Initiated successfully with result: "+status.getStatusMessage());
return;
}
TurnBasedMatch match = result.getMatch();
// If this player is not the first player in this match, continue.
if (match.getData() != null) {
showTurnUI(match);
return;
}
// Otherwise, this is the first player. Initialize the game state.
initGame(match);
// Let the player take the first turn
showTurnUI(match);
}
public void showTurnUI(TurnBasedMatch match){
if(match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE){
if(match.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN){
turnBasedMatchData = match.getData();
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(), "score:400".getBytes(Charset.forName("UTF-16")),null).setResultCallback(updateMatchResult());
}
}
}
public void initGame(TurnBasedMatch match){
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),"score:605".getBytes(Charset.forName("UTF-16")),match.getParticipantId(Games.Players.getCurrentPlayerId(mHelper.getApiClient()))).setResultCallback(updateMatchResult());
}
public ResultCallback<TurnBasedMultiplayer.UpdateMatchResult> updateMatchResult(){
return null;
}
#Override
public void onTurnBasedMatchReceived(TurnBasedMatch turnBasedMatch) {
Log.d("turn-based","Player played his turn");
}
#Override
public void onTurnBasedMatchRemoved(String s) {
}
}
}
Also it would helpful if some can properly explain how to continue a game a game from start and when to submit score and how.
Figured it out. This is how you can do it.
public byte[] persist() {
JSONObject retVal = new JSONObject();
try {
retVal.put("turnCounter", 2);
retVal.put("score1",100);
retVal.put("score2",200);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String st = retVal.toString();
Log.d(TAG, "==== PERSISTING\n" + st);
return st.getBytes(Charset.forName("UTF-8"));
}
Games.TurnBasedMultiplayer.takeTurn(mHelper.getApiClient(),match.getMatchId(),persist(),null).setResultCallback(updateMatchResult());
I wrote a custom plugin to read blocks of data from an NfcA(i.e.non-ndef) tag. It seems to work fine , but only after the second scan. I am using Activity intent to derive the "NfcAdapter.EXTRA_TAG" to later use it for reading the values. I am also updating the Intents in onNewIntent(). OnNewIntent gets called after the second scan and after that I get result all the time.But in the first scan onNewIntent does not gets called, hence I end up using the Activity tag that does not have "NfcAdapter.EXTRA_TAG", hence I get null. Please see the my code below.
SE_NfcA.java(my native code for plugin)
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
String Result = "";
String TypeOfTalking = "";
if (action.contains("TalkToNFC"))
{
JSONObject arg_object = args.getJSONObject(0);
TypeOfTalking = arg_object.getString("type");
if(TypeOfTalking != "")
{
if (TypeOfTalking.contains("readBlock"))
{
if(TypeOfTalking.contains("#"))
{
try
{
String[] parts = TypeOfTalking.split("#");
int index = Integer.parseInt(parts[1]);
Result = Readblock(cordova.getActivity().getIntent(),(byte)index);
callbackContext.success(Result);
}
catch(Exception e)
{
callbackContext.error("Exception Reading "+ TypeOfTalking + "due to "+ e.toString());
return false;
}
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
return true;
}
#Override
public void onNewIntent(Intent intent) {
ShowAlert("onNewIntent called");
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
super.onNewIntent(intent);
getActivity().setIntent(intent);
savedTag = tagFromIntent;
savedIntent = intent;
}
#Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getActivity().getIntent());
super.onPause(multitasking);
if (multitasking) {
// nfc can't run in background
stopNfc();
}
}
#Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getActivity().getIntent());
super.onResume(multitasking);
startNfc();
}
public String Readblock(Intent Intent,byte block) throws IOException{
byte[] response = new byte[]{};
if(Intent != null)
{
Tag myTag = Intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if(savedTag != null)
myTag = savedTag;
if(myTag != null)
{
try{
Reader nTagReader = new Reader(myTag);
nTagReader.close();
nTagReader.connect();
nTagReader.SectorSelect(Sector.Sector0);
response = nTagReader.fast_read(block, block);
nTagReader.close();
return ConvertH(response);
}catch(Exception e){
ShowAlert(e.toString());
}
}
else
ShowAlert("myTag is null.");
}
return null;
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && !getActivity().isFinishing()) {
try {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
} catch (IllegalStateException e) {
// issue 110 - user exits app with home button while nfc is initializing
Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(getActivity());
} catch (IllegalStateException e) {
// issue 125 - user exits app with back button while nfc
Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating.");
}
}
}
});
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
}
My index.js file
nfc.addTagDiscoveredListener(
function(nfcEvent){
console.log(nfcEvent.tag.id);
alert(nfcEvent.tag.id);
window.echo("readBlock#88");//call to plugin
},
function() {
alert("Listening for NFC tags.");
},
function() {
alert("NFC activation failed.");
}
);
SE_NfcA.js(plugin interface for interaction b/w index.js and SE_NfcA.java)
window.echo = function(natureOfTalk)
{
alert("Inside JS Interface, arg =" + natureOfTalk);
cordova.exec(function(result){alert("Result is : "+result);},
function(error){alert("Some Error happened : "+ error);},
"SE_NfcA","TalkToNFC",[{"type": natureOfTalk}]);
};
I guess I have messed up with the Intents/Activity Life-Cycle, please help. TIA!
I found a tweak/hack and made it to work.
Before making any call to read or write, I made one dummy Initialize call.
window.echo("Initialize");
window.echo("readBlock#88");//call to plugin to read.
And in the native code of the plugin, on receiving the "Initialize" token I made a startNFC() call.
else if(TypeOfTalking.equalsIgnoreCase("Initialize"))
{
startNfc();
}
I am trying to get data from Onyx2(Fingertip Oximeter) via Bluetooth using Health Device Profile and sample, which can be found at Android Developers site. But I am getting the following error
E/BluetoothEventLoop.cpp(432): onHealthDeviceConnectionResult: D-Bus error: org.bluez.Error.HealthError (Error getting remote SDP records).
What can be a reason of this problem?
BTW, approximately 1 time out of 50, I get the data.
// Callbacks to handle connection set up and disconnection clean up.
private final BluetoothProfile.ServiceListener mBluetoothServiceListener =
new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.HEALTH) {
mBluetoothHealth = (BluetoothHealth) proxy;
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "onServiceConnected to profile: " + profile);
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEALTH) {
mBluetoothHealth = null;
}
}
};
private final BluetoothHealthCallback mHealthCallback = new BluetoothHealthCallback() {
// Callback to handle application registration and unregistration events. The service
// passes the status back to the UI client.
public void onHealthAppConfigurationStatusChange(BluetoothHealthAppConfiguration config,
int status) {
if (status == BluetoothHealth.APP_CONFIG_REGISTRATION_FAILURE) {
mHealthAppConfig = null;
sendMessage(STATUS_HEALTH_APP_REG, RESULT_FAIL);
} else if (status == BluetoothHealth.APP_CONFIG_REGISTRATION_SUCCESS) {
mHealthAppConfig = config;
sendMessage(STATUS_HEALTH_APP_REG, RESULT_OK);
} else if (status == BluetoothHealth.APP_CONFIG_UNREGISTRATION_FAILURE ||
status == BluetoothHealth.APP_CONFIG_UNREGISTRATION_SUCCESS) {
sendMessage(STATUS_HEALTH_APP_UNREG,
status == BluetoothHealth.APP_CONFIG_UNREGISTRATION_SUCCESS ?
RESULT_OK : RESULT_FAIL);
}
}
// Callback to handle channel connection state changes.
// Note that the logic of the state machine may need to be modified based on the HDP device.
// When the HDP device is connected, the received file descriptor is passed to the
// ReadThread to read the content.
public void onHealthChannelStateChange(BluetoothHealthAppConfiguration config,
BluetoothDevice device, int prevState, int newState, ParcelFileDescriptor fd,
int channelId) {
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, String.format("prevState\t%d ----------> newState\t%d",
prevState, newState));
if (prevState == BluetoothHealth.STATE_CHANNEL_CONNECTING &&
newState == BluetoothHealth.STATE_CHANNEL_CONNECTED) {
if (config.equals(mHealthAppConfig)) {
mChannelId = channelId;
sendMessage(STATUS_CREATE_CHANNEL, RESULT_OK);
(new ReadThread(fd)).start();
} else {
sendMessage(STATUS_CREATE_CHANNEL, RESULT_FAIL);
}
} else if (prevState == BluetoothHealth.STATE_CHANNEL_CONNECTING &&
newState == BluetoothHealth.STATE_CHANNEL_DISCONNECTED) {
sendMessage(STATUS_CREATE_CHANNEL, RESULT_FAIL);
} else if (newState == BluetoothHealth.STATE_CHANNEL_DISCONNECTED) {
if (config.equals(mHealthAppConfig)) {
sendMessage(STATUS_DESTROY_CHANNEL, RESULT_OK);
} else {
sendMessage(STATUS_DESTROY_CHANNEL, RESULT_FAIL);
}
}
}
};
// Initiates application registration through {#link
// BluetoothHDPService}.
Button registerAppButton = (Button) findViewById(R.id.button_register_app);
registerAppButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage(BluetoothHDPService.MSG_REG_HEALTH_APP,
HEALTH_PROFILE_SOURCE_DATA_TYPE);
}
});
// Initiates application unregistration through {#link
// BluetoothHDPService}.
Button unregisterAppButton = (Button) findViewById(R.id.button_unregister_app);
unregisterAppButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage(BluetoothHDPService.MSG_UNREG_HEALTH_APP, 0);
}
});
// Initiates channel creation through {#link BluetoothHDPService}. Some
// devices will
// initiate the channel connection, in which case, it is not necessary
// to do this in the
// application. When pressed, the user is asked to select from one of
// the bonded devices
// to connect to.
Button connectButton = (Button) findViewById(R.id.button_connect_channel);
connectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAllBondedDevices = (BluetoothDevice[]) mBluetoothAdapter
.getBondedDevices().toArray(new BluetoothDevice[0]);
if (mAllBondedDevices.length > 0) {
int deviceCount = mAllBondedDevices.length;
if (mDeviceIndex < deviceCount)
mDevice = mAllBondedDevices[mDeviceIndex];
else {
mDeviceIndex = 0;
mDevice = mAllBondedDevices[0];
}
String[] deviceNames = new String[deviceCount];
int i = 0;
for (BluetoothDevice device : mAllBondedDevices) {
deviceNames[i++] = device.getName();
}
SelectDeviceDialogFragment deviceDialog = SelectDeviceDialogFragment
.newInstance(deviceNames, mDeviceIndex);
deviceDialog.show(getFragmentManager(), "deviceDialog");
}
}
});
// Initiates channel disconnect through {#link BluetoothHDPService}.
Button disconnectButton = (Button) findViewById(R.id.button_disconnect_channel);
disconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
disconnectChannel();
}
});
registerReceiver(mReceiver, initIntentFilter());
}
// Sets up communication with {#link BluetoothHDPService}.
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mHealthServiceBound = true;
Message msg = Message.obtain(null,
BluetoothHDPService.MSG_REG_CLIENT);
msg.replyTo = mMessenger;
mHealthService = new Messenger(service);
try {
mHealthService.send(msg);
} catch (RemoteException e) {
Log.w(TAG, "Unable to register client to service.");
e.printStackTrace();
I remember that Android HDP demo app had some problem about not closing bluetooth connections when terminated.
One test that you can do to verify this is:
Turn off bluetooth of your android.
Turn it on again.
Pair with the health device (in android settings)
Start your android application.
Try to connect and transfer data with health device.
If these steps works consistently when repeated, i'm almost sure it has something to do with the app not releasing resources like i sad before.
I have an Android application in When application go in background and headphone remove from phone alarm start.All is fine on foreground,but when application go in background its not work.I wrote code on activity onPause() as below
#Override
protected void onPause() {
try{
super.onPause();
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")) {
int state = intent.getIntExtra("state", 0);
if (isHeadPhoneAttached && state == 0) {
isHeadPhoneAttached = false;
if (isTriggered) {
createNotification();
initTimerCounter();
makeToat();
/*handler.removeCallbacks(sendUpdatesToUI);*/
/*callTriggerActivity();*/
/*showDialog(Headphone_DIALOG);*/
}
} else if (!isHeadPhoneAttached && state == 1) {
isHeadPhoneAttached = true;
}
}
}
}, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
/*createNotification();
initTimerCounter() ;*/
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
but it's not working.Please anybody give me some idea.
You can't be sure if your application is running in the background so registering an BroadcastReceiver in the onPause method of an Activity is general bad practice.
You should use a Service instead
Wanted to stop a thread doing some downloads.
The code below work fine when i only have the stopNow = true; and no blocking occur.
I create the boolean stopNow = false; as a field in my IntentService.
Since stopNow only work when the connection is ongoing in the while loop
but it does not work if f.ex connection stales and start to block.
I wanted to add this code to really stop the blocking.
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
The question is if this is asynchronous so if the execution is ongoing in the
while loop the stopNow = true; will stop it and i can put a sleep(5000) after the stopNow = true; and then the if(socket != null) will be true only if the stopNow had no effect.
hope you follow me..
BroadcastReceiver that are located inside the run():
private class MyIncomingListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Consts.COM_CARLSBERG_STOPOUTGOING)) {
String b = intent.getStringExtra(Consts.COM_CARLSBERG_BATCHUUID);
if(b != null){
if(b.equals(batch.batchUuid)){
stopNow = true;
// sleep(5000) wait for stopNow to take effect
// if socket=null then stopNow did it's job
// if socket is alive then there is blocking to unblock
try{
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
} catch (Exception e) {}
}
}
}
}
}
this is actually working good so far
stopNow = true;
try{
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
} catch (Exception e) {}
public final void stop ()
Since: API Level 1
This method is deprecated.
because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.
Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
Intent intent= new Intent(SplashActivity.this,LoginViewController.class);
startActivity(intent);
stop();
}