Google Achievements Unlock But Don't Save - android

I added achievements to my Google Play game following Google's tutorial. They unlock fine and if I display achievements in-game immediately they show up. If I quit the game and go to the Google Game's app they don't show up and they disappear from in-game also. Any ideas? I've tried multiple accounts. Thanks!
package com.b1stable.tth;
import java.io.File;
import java.io.FileFilter;
import java.util.Locale;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.FileSystems;
import java.util.Vector;
import android.os.Bundle;
import android.os.Build;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Vibrator;
import android.os.VibrationEffect;
import android.util.Log;
import android.view.Surface;
import android.view.Gravity;
import org.libsdl.app.SDLActivity;
import com.b1stable.tth.License_Viewer_Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.games.AchievementsClient;
import com.google.android.gms.games.AnnotatedData;
import com.google.android.gms.games.EventsClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.LeaderboardsClient;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.PlayersClient;
import com.google.android.gms.games.event.Event;
import com.google.android.gms.games.event.EventBuffer;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Task.*;
public class TTH_Activity extends SDLActivity
{
final static int LICENSE_REQUEST = 1;
native static void resume_after_showing_license();
native static void resume_after_showing_achievements();
native static void pause();
native static void resume();
// Client used to sign in with Google APIs
private GoogleSignInClient mGoogleSignInClient;
private AchievementsClient mAchievementsClient = null;
private boolean signin_failed = false;
// request codes we use when invoking an external activity
private static final int RC_UNUSED = 5001;
private static final int RC_SIGN_IN = 9001;
// This is so the screen is never cleared pure black, only shim::black (r:35, g:30, b:60)
static boolean paused = false;
private static final String TAG = "TTH";
#Override
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LICENSE_REQUEST) {
if (data != null) {
if (resultCode == RESULT_OK && data.getExtras().getString("MESSAGE").equals("OK")) {
show_license_result = 0;
}
else if (resultCode == RESULT_CANCELED && data.getExtras().getString("MESSAGE").equals("FAIL")) {
show_license_result = 1;
}
else {
show_license_result = 1;
}
}
else {
show_license_result = 1;
}
resume_after_showing_license();
}
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
onConnected(signedInAccount);
}
else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "An error occurred!";
}
new AlertDialog.Builder(this).setMessage(message).setNeutralButton(android.R.string.ok, null).show();
onDisconnected();
}
}
}
public void onStart() {
super.onStart();
}
#Override
public void onStop()
{
super.onStop();
pause();
}
#Override
public void onRestart()
{
super.onRestart();
resume();
}
#Override
public void onResume()
{
super.onResume();
signInSilently();
}
#Override
public void onPause()
{
super.onPause();
mAchievementsClient = null;
}
#Override
public void onPostResume()
{
super.onPostResume();
paused = true;
}
public void logString(String s)
{
Log.d("TTH", s);
}
public String getAppdataDir()
{
return getFilesDir().getAbsolutePath();
}
public String getSDCardDir()
{
File f = getExternalFilesDir(null);
if (f != null) {
return f.getAbsolutePath();
}
else {
return getFilesDir().getAbsolutePath();
}
}
static int show_license_result;
public void showLicense()
{
show_license_result = -1;
Intent intent = new Intent(this, License_Viewer_Activity.class);
startActivityForResult(intent, LICENSE_REQUEST);
}
public int getShowLicenseResult()
{
return show_license_result;
}
/*
public void openURL(String url)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
*/
public void rumble(int milliseconds)
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null && v.hasVibrator()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
}
else {
v.vibrate(milliseconds);
}
}
}
public boolean has_touchscreen()
{
return getPackageManager().hasSystemFeature("android.hardware.touchscreen");
}
public boolean has_vibrator()
{
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
return v.hasVibrator();
}
else {
return false;
}
}
public void start_draw()
{
if (paused) {
paused = false;
}
}
public String get_android_language()
{
return Locale.getDefault().getLanguage();
}
private static File[] list_dir_files = null;
public void list_dir_start(String path)
{
try {
int slash = path.lastIndexOf('/');
final String glob = path.substring(slash+1).replace("*", ".*"); // +1 works even if not found (-1+1 == 0)
String dir = path.substring(0, slash);
File f = new File(dir);
list_dir_files = f.listFiles(new FileFilter() {
public boolean accept(File f)
{
try {
if (f.getName().matches(glob)) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
Log.d("TTH", "list_dir_start FileFilter throwing " + e.getMessage());
return false;
}
}
});
}
catch (Exception e) {
list_dir_files = null;
Log.d("TTH", "list_dir_start throwing " + e.getMessage());
}
}
public String list_dir_next()
{
if (list_dir_files == null) {
return "";
}
else if (list_dir_files.length == 0) {
list_dir_files = null;
return "";
}
else {
File f = list_dir_files[0];
String name = f.getName();
if (list_dir_files.length == 1) {
list_dir_files = null;
}
else {
File[] new_list = new File[list_dir_files.length-1];
for (int i = 1; i < list_dir_files.length; i++) {
new_list[i-1] = list_dir_files[i];
}
list_dir_files = new_list;
}
return name;
}
}
private static final String ARC_DEVICE_PATTERN = ".+_cheets|cheets_.+";
public boolean is_chromebook()
{
// Google uses this, so should work?
return Build.DEVICE != null && Build.DEVICE.matches(ARC_DEVICE_PATTERN);
}
private static final int RC_ACHIEVEMENT_UI = 9003;
public boolean show_achievements()
{
if (mAchievementsClient == null) {
return false;
}
mAchievementsClient.getAchievementsIntent().addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, RC_ACHIEVEMENT_UI);
resume_after_showing_achievements();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
resume_after_showing_achievements();
}
}).addOnCompleteListener(new OnCompleteListener<Intent>() {
#Override
public void onComplete(Task<Intent> task) {
resume_after_showing_achievements();
}
});
return true;
}
public void achieve(String id)
{
if (mAchievementsClient != null) {
mAchievementsClient.unlock(id);
}
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
private void signInSilently() {
if (signin_failed == true || mAchievementsClient != null) {
return;
}
GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
// Already signed in.
// The signed in account is stored in the 'account' variable.
//GoogleSignInAccount signedInAccount = account;
onConnected(account);
}
else {
// Haven't been signed-in before. Try the silent sign-in first.
GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
signInClient.silentSignIn().addOnCompleteListener(
this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
onConnected(signedInAccount);
}
else {
// Player will need to sign-in explicitly using via UI.
// See [sign-in best practices](http://developers.google.com/games/services/checklist) for guidance on how and when to implement Interactive Sign-in,
// and [Performing Interactive Sign-in](http://developers.google.com/games/services/android/signin#performing_interactive_sign-in) for details on how to implement
// Interactive Sign-in.
startSignInIntent();
}
}
}
);
}
}
public void start_google_play_games_services() {
/*
runOnUiThread(new Runnable() {
public void run() {
signInSilently();
}
});
*/
}
private void onConnected(GoogleSignInAccount googleSignInAccount) {
Log.d(TAG, "onConnected(): connected to Google APIs");
GamesClient gamesClient = Games.getGamesClient(this, googleSignInAccount);
gamesClient.setViewForPopups(findViewById(android.R.id.content));
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
mAchievementsClient = Games.getAchievementsClient(this, googleSignInAccount);
}
private void onDisconnected() {
Log.d(TAG, "onDisconnected()");
mAchievementsClient = null;
signin_failed = true;
}
}

Related

TTS onUtteranceCompleted not working in Android

I am working on speechRecognizer module in android integrated with dialogflow. I have almost completed the integration and it's working fine but facing one issue. The issue is when TTS is speaking the response, before completing the speech mic gets enabled and it capture the response also instead of user utterance only.
So I want to know how can I get to know that TTS finished speaking the response? I have tried Google solution by using onUtteranceCompleted() method and also I have tried on setOnUtteranceProgressListener() method but doesn't seems to be working. I want to implement these methods in asynctask So that it can be done in background. How can I do that?
Here is the code that I have tried:
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import ai.api.PartialResultsListener;
import ai.api.android.AIConfiguration;
import ai.api.android.GsonFactory;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
import ai.api.ui.AIDialog;
import android.os.AsyncTask;
import com.google.gson.Gson;
public class VoiceActivity extends AppCompatActivity implements View.OnClickListener, TextToSpeech.OnInitListener, RecognitionListener {
private AIDialog.AIDialogListener resultsListener;
private static final int REQUEST_AUDIO_PERMISSIONS_ID = 33;
private Gson gson = GsonFactory.getGson();
private ListView wordList;
TextView txtmain;
private static final int VR_REQUEST = 999;
//Log tag for output information
private final String LOG_TAG = "SpeechRepeatActivity";//***enter your own tag here***
//variable for checking TTS engine data on user device
private int MY_DATA_CHECK_CODE = 0;
//Text To Speech instance
private TextToSpeech tts;
AIButton aiButton;
EditText time;
TextView matchcall;
// private SpeechRecognizer speech = null;
private Intent recognizerIntent;
TextView tvOutput ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice);
aiButton = (AIButton) findViewById(R.id.speech_btn);
txtmain =findViewById(R.id.txtmain);
wordList = findViewById(R.id.word_list);
tvOutput = findViewById(R.id.tvOutput);
time = (EditText) findViewById(R.id.in_time);
matchcall = (TextView) findViewById(R.id.matchcall);
final AsyncTaskRunner runner = new AsyncTaskRunner();
initService();
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (intActivities.size() != 0) {
//speech recognition is supported - detect user button clicks
aiButton.setOnClickListener(this);
//prepare the TTS to repeat chosen words
Intent checkTTSIntent = new Intent();
//check TTS data
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
//start the checking Intent - will retrieve result in onActivityResult
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
} else {
//speech recognition not supported, disable button and output message
aiButton.setEnabled(false);
Toast.makeText(this, "Oops - Speech recognition not supported!", Toast.LENGTH_LONG).show();
}
}
private void setAIButtonCallback(final AIButton aiButton) {
aiButton.setResultsListener(new AIButton.AIButtonListener() {
#Override
public void onResult(final AIResponse result) {
if (resultsListener != null) {
resultsListener.onResult(result);
Log.e(LOG_TAG,"onResult=="+result.getResult().getResolvedQuery());
final String speech = result.getResult().getFulfillment().getSpeech();
tvOutput.setText(speech);
}
}
#Override
public void onError(final AIError error) {
if (resultsListener != null) {
resultsListener.onError(error);
Log.e(LOG_TAG,"onError=="+error);
}
}
#Override
public void onCancelled() {
if (resultsListener != null) {
resultsListener.onCancelled();
Log.e(LOG_TAG,"onCancelled==");
}
}
});
aiButton.setPartialResultsListener(new PartialResultsListener() {
#Override
public void onPartialResults(final List<String> partialResults) {
final String result = partialResults.get(0);
if (!TextUtils.isEmpty(result)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
txtmain.setText(result);
}
});
}
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.speech_btn) {
//listen for results
listenToSpeech();
}
}
#Override
public void onInit(int status) {
//if successful, set locale
if (status == TextToSpeech.SUCCESS)
tts.setLanguage(Locale.UK);//***choose your own locale here***
}
private void listenToSpeech() {
SpeechRecognizer speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
//start listening
speech.startListening(recognizerIntent);
}
#Override
public void onResults(Bundle results) {
Log.i(LOG_TAG, "onResults");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
/* wordList.setAdapter(new ArrayAdapter<String>(this, R.layout.word, matches));
new Handler().post(new Runnable() {
#Override
public void run() {
wordList.performItemClick(
wordList.getChildAt(0),
0,
wordList.getAdapter().getItemId(0));
wordList.getChildAt(0).setBackgroundColor(0xFFD3D3D3);
}
});*/
String wordChosen = matches.get(0);
tvOutput.setText(wordChosen);
try {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(wordChosen);
// aiButton.textRequest(text);
//runner.doInBackground(text);
} catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncTaskRunner extends AsyncTask<String, AIResponse, AIResponse> {
private AIResponse resp;
ProgressDialog progressDialog;
#Override
protected AIResponse doInBackground(String... params) {
Log.e(LOG_TAG,"doInBackground=="+params[0]);
try {
resp = aiButton.textRequest(String.valueOf(params[0]));
}
catch (Exception e) {
e.printStackTrace();
}
return resp;
}
protected void onPostExecute(AIResponse result) {
Log.e(LOG_TAG,"onPostExecute== result=="+result.getResult().getFulfillment().getSpeech());
// execution of result of Long time consuming operation
findViewById(R.id.progBar).setVisibility(View.GONE);
txtmain.setText(result.getResult().getFulfillment().getSpeech());
String speech = result.getResult().getFulfillment().getSpeech();
tts.speak( speech, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(VoiceActivity.this, speech, Toast.LENGTH_SHORT).show();
listenToSpeech();
}
#Override
protected void onPreExecute() {
Log.e(LOG_TAG,"onPreExecute==");
findViewById(R.id.progBar).setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//check speech recognition result
if (requestCode == VR_REQUEST && resultCode == RESULT_OK)
{
//store the returned word list as an ArrayList
ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//set the retrieved list to display in the ListView using an ArrayAdapter
wordList.setAdapter(new ArrayAdapter<String>(this, R.layout.word, suggestedWords));
/*new Handler().post(new Runnable() {
#Override
public void run() {
wordList.performItemClick(
wordList.getChildAt(0),
0,
wordList.getAdapter().getItemId(0));
wordList.getChildAt(0).setBackgroundColor(0xFFD3D3D3);
}
});*/
tvOutput.setText(suggestedWords.get(0));
}
if (requestCode == MY_DATA_CHECK_CODE)
{
//we have the data - create a TTS instance
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
tts = new TextToSpeech(this, this);
//data not installed, prompt the user to install it
else
{
//intent will take user to TTS download page in Google Play
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
//call superclass method
super.onActivityResult(requestCode, resultCode, data);
}
private void initService() {
final AIConfiguration config = new AIConfiguration("a73d5e88477e4926ae84af46f24e0aaa",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.Google);
aiButton.initialize(config);
setAIButtonCallback(aiButton);
Log.i(LOG_TAG, "initService:::::: ");
}
#Override
protected void onPause() {
super.onPause();
// speech.stopListening();
// use this method to disconnect from speech recognition service
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
5000
);
// Not destroying the SpeechRecognition object in onPause method would block other apps from using SpeechRecognition service
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
Log.i(LOG_TAG, "stop");
super.onStop();
/* if (speech != null) {
speech.destroy();*/
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//}
#Override
protected void onStart() {
super.onStart();
checkAudioRecordPermission();
}
protected void checkAudioRecordPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_AUDIO_PERMISSIONS_ID);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_AUDIO_PERMISSIONS_ID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}
}
}
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
//speech.stopListening();
}
#Override
public void onError(int errorcode) {
String errorMessage = getErrorText(errorcode);
Log.i(LOG_TAG, "FAILED " + errorMessage);
// speech.stopListening();
// listenToSpeech();
}
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
//speech.stopListening();
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
}

Create Remote HttpServer using nanoHttpd

I am creating a httpserver using NanoHttpd library. When I am running it on local it is working fine. but when i am trying to create httpserver using Hostname.This is giving following Error.
bind failed: EADDRNOTAVAIL (Cannot assign requested address)
Here is My MainActivity
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final int DEFAULT_PORT = 8080;
private AndroidWebServer androidWebServer;
private BroadcastReceiver broadcastReceiverNetworkState;
private static boolean isStarted = false;
private CoordinatorLayout coordinatorLayout;
private EditText editTextPort;
private FloatingActionButton floatingActionButtonOnOff;
private View textViewMessage;
private TextView textViewIpAccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setElevation(0);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
editTextPort = (EditText) findViewById(R.id.editTextPort);
textViewMessage = findViewById(R.id.textViewMessage);
textViewIpAccess = (TextView) findViewById(R.id.textViewIpAccess);
setIpAccess();
floatingActionButtonOnOff = (FloatingActionButton) findViewById(R.id.floatingActionButtonOnOff);
floatingActionButtonOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isConnectedInWifi()) {
if (!isStarted && startAndroidWebServer()) {
isStarted = true;
textViewMessage.setVisibility(View.VISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this, R.color.colorGreen));
editTextPort.setEnabled(false);
} else if (stopAndroidWebServer()) {
isStarted = false;
textViewMessage.setVisibility(View.INVISIBLE);
floatingActionButtonOnOff.setBackgroundTintList(ContextCompat.getColorStateList(MainActivity.this, R.color.colorRed));
editTextPort.setEnabled(true);
}
} else {
Snackbar.make(coordinatorLayout, getString(R.string.wifi_message), Snackbar.LENGTH_LONG).show();
}
}
});
initBroadcastReceiverNetworkStateChanged();
}
private boolean startAndroidWebServer() {
if (!isStarted) {
int port = getPortFromEditText();
try {
if (port == 0) {
throw new Exception();
}
androidWebServer = new AndroidWebServer(8080);
androidWebServer.start();
return true;
} catch (Exception e) {
Log.e("this is exception", e.getMessage());
}
}
return false;
}
private boolean stopAndroidWebServer() {
if (isStarted && androidWebServer != null) {
androidWebServer.stop();
return true;
}
return false;
}
private void setIpAccess() {
textViewIpAccess.setText(getIpAccess());
}
private void initBroadcastReceiverNetworkStateChanged() {
final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
broadcastReceiverNetworkState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setIpAccess();
}
};
super.registerReceiver(broadcastReceiverNetworkState, filters);
}
private String getIpAccess() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
return "http://" + formatedIpAddress + ":";
}
private int getPortFromEditText() {
String valueEditText = editTextPort.getText().toString();
return (valueEditText.length() > 0) ? Integer.parseInt(valueEditText) : DEFAULT_PORT;
}
public boolean isConnectedInWifi() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()
&& wifiManager.isWifiEnabled() && networkInfo.getTypeName().equals("WIFI")) {
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent evt) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isStarted) {
new AlertDialog.Builder(this)
.setTitle(R.string.warning)
.setMessage(R.string.dialog_exit_message)
.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.show();
} else {
finish();
}
return true;
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
stopAndroidWebServer();
isStarted = false;
if (broadcastReceiverNetworkState != null) {
unregisterReceiver(broadcastReceiverNetworkState);
}
}
}
This is my class how I am starting HttpServer
import android.os.Environment;
import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.request.Method;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class AndroidWebServer extends NanoHTTPD {
public AndroidWebServer(int port) {
super(port);
}
public AndroidWebServer(String hostname, int port) {
super(hostname, port);
}
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
String msg = "<html><body><h1>This is all you should know</h1>\n";
return Response.newFixedLengthResponse(msg);
}
private Response uploadImage() { // this method you can use to upload file(audio,Video aur image)
FileInputStream fis = null;
File file = null;
try {
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg");
fis = new FileInputStream(file.getAbsoluteFile());
return new Response(Status.OK, "image/jpg", fis, file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}

Google calendar API fragment

I've been trying to implement the google calendar on a fragment but unsuccessful.
This code provided by google works fine in one activity, but I'm using ViewPager with tabs.
When the button is press don't show data retrive from google calendar, the same code in activity (without inflate rootview) works fine..
package com.example.myapplication;
import android.Manifest;
import android.support.v4.app.Fragment;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import static android.app.Activity.RESULT_OK;
public class Tab1 extends Fragment implements EasyPermissions.PermissionCallbacks {
GoogleAccountCredential mCredential;
private TextView mOutputText;
private Button mCallApiButton;
ProgressDialog mProgress;
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
private static final String BUTTON_TEXT = "Atualizar Calendario";
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout activityLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
activityLayout.setOrientation(LinearLayout.VERTICAL);
activityLayout.setPadding(16, 16, 16, 16);
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mCallApiButton = new Button(getActivity());
mCallApiButton.setText(BUTTON_TEXT);
mCallApiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallApiButton.setEnabled(false);
mOutputText.setText("");
getResultsFromApi();
mCallApiButton.setEnabled(true);
}
});
activityLayout.addView(mCallApiButton);
mOutputText = new TextView(getActivity());
mOutputText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
mOutputText.setLayoutParams(tlp);
mOutputText.setText("");
mOutputText.setPadding(16, 16, 16, 16);
mOutputText.setVerticalScrollBarEnabled(true);
mOutputText.setMovementMethod(new ScrollingMovementMethod());
activityLayout.addView(mOutputText);
mProgress = new ProgressDialog(getActivity());
mProgress.setMessage("A conferir Calendario Google");
mCredential = GoogleAccountCredential.usingOAuth2(getActivity().getApplicationContext(), Arrays.asList(SCOPES)).setBackOff(new ExponentialBackOff());
return (activityLayout);
}
private void getResultsFromApi() {
if (! isGooglePlayServicesAvailable()) {
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
//VAI POR ESTE
} else if (! isDeviceOnline()) {
mOutputText.setText("No network connection available.");
} else {
new MakeRequestTask(mCredential).execute();
}
}
#AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.GET_ACCOUNTS)) {
String accountName = getActivity().getPreferences(Context.MODE_PRIVATE).getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
} else {
EasyPermissions.requestPermissions(getActivity(), "This app needs to access your Google account (via Contacts).", REQUEST_PERMISSION_GET_ACCOUNTS, Manifest.permission.GET_ACCOUNTS);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
mOutputText.setText("This app requires Google Play Services. Please install " + "Google Play Services on your device and relaunch this app.");
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, getActivity());
}
#Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Do nothing.
}
#Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Do nothing.
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(getActivity());
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(getActivity());
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
getActivity(),
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private com.google.api.services.calendar.Calendar mService = null;
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.calendar.Calendar.Builder(transport, jsonFactory, credential).setApplicationName("Google Calendar API Android Quickstart").build();
}
#Override
protected List<String> doInBackground(Void... params) {
try {
return getDataFromApi();
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
/**
* Fetch a list of the next 10 events from the primary calendar.
* #return List of Strings describing returned events.
* #throws IOException
*/
private List<String> getDataFromApi() throws IOException {
// List the next 10 events from the primary calendar.
DateTime now = new DateTime(System.currentTimeMillis());
List<String> eventStrings = new ArrayList<String>();
Events events = mService.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
List<Event> items = events.getItems();
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
eventStrings.add(
String.format("%s (%s)", event.getSummary(), start));
}
return eventStrings;
}
#Override
protected void onPreExecute() {
mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
mOutputText.setText("No results returned.");
} else {
output.add(0, "Data retrieved using the Google Calendar API:");
mOutputText.setText(TextUtils.join("\n", output));
}
}
#Override
protected void onCancelled() {
mProgress.hide();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
showGooglePlayServicesAvailabilityErrorDialog(((GooglePlayServicesAvailabilityIOException) mLastError).getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) {
//startActivityForResult(
// ((UserRecoverableAuthIOException) mLastError).getIntent(),
// MainActivity.REQUEST_AUTHORIZATION);
} else {
mOutputText.setText("The following error occurred:\n" + mLastError.getMessage());
}
} else {
mOutputText.setText("Request cancelled.");
}
}
}
}

Android Fingerprint code is not working in a service class

I am following the Google sample code. The below code is working fine when I used in a Activity class. But when I use the same code in a service class is not working. Can't receiving a call back from FingerprintUiHelper.Callback on both method onAuthenticated() and onError(). I have write service that draw an dialog on other apps I want to dismiss the dialog when the fingerprint is authenticated.
Here is my AppCheckService class
import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v4.app.ActivityCompat;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.takwolf.android.lock9.Lock9View;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.inject.Inject;
public class AppCheckServices extends Service {
public static String currentApp = "";
public static String previousApp = "";
ImageView imageView;
SharedPreference sharedPreference;
SharedPreferences sharedPreferences;
List<String> pakageName;
String currentProfile;
private Context context = null;
private Timer timer;
private WindowManager windowManager;
private static final String KEY_NAME = "my_key";
private Dialog dialog;
FingerprintUiHelper.FingerprintUiHelperBuilder mFingerprintUiHelperBuilder;
private FingerprintManagerCompat.CryptoObject mCryptoObject;
private KeyStore mKeyStore;
private Cipher mCipher;
private FingerprintUiHelper mFingerprintUiHelper;
#Inject
FingerprintManagerCompat mFingerprintManager;
#Inject
SharedPreferences mSharedPreferences;
private TimerTask updateTask = new TimerTask() {
#Override
public void run() {
String currentlyActiveProfile = sharedPreferences.getString("ActiveProfile", "");
if (sharedPreference != null) {
pakageName = sharedPreference.getLocked(context, currentlyActiveProfile);
}
if (isConcernedAppIsInForeground()) {
if (imageView != null) {
imageView.post(new Runnable() {
public void run() {
if (!currentApp.matches(previousApp)) {
showUnlockDialog();
previousApp = currentApp;
}
}
});
}
} else {
if (imageView != null) {
imageView.post(new Runnable() {
public void run() {
hideUnlockDialog();
}
});
}
}
}
};
#Override
public void onCreate() {
super.onCreate();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
currentProfile = sharedPreferences.getString("ActiveProfile", null);
if (currentProfile != null) {
Log.i("jcheckvalues", currentProfile);
}
context = getApplicationContext();
sharedPreference = new SharedPreference();
if (sharedPreference != null) {
pakageName = sharedPreference.getLocked(context, currentProfile);
}
timer = new Timer("AppCheckServices");
timer.schedule(updateTask, 500L, 500L);
final Tracker t = ((AppLockApplication) getApplication()).getTracker(AppLockApplication.TrackerName.APP_TRACKER);
t.setScreenName(AppLockConstants.APP_LOCK);
t.send(new HitBuilders.AppViewBuilder().build());
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
imageView = new ImageView(this);
imageView.setVisibility(View.GONE);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.CENTER;
params.x = ((getApplicationContext().getResources().getDisplayMetrics().widthPixels) / 2);
params.y = ((getApplicationContext().getResources().getDisplayMetrics().heightPixels) / 2);
windowManager.addView(imageView, params);
}
void showUnlockDialog() {
showDialog();
}
void hideUnlockDialog() {
previousApp = "";
try {
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
void showDialog() {
if (context == null)
context = getApplicationContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String PasswordType = sharedPreferences.getString("PasswordType", "");
if (PasswordType.equals("pattern")) {
showPatternDialog(context);
} else if (PasswordType.equals("pin")) {
// showPinDialog(context);
}
}
private void showPatternDialog(Context context) {
///////////////////////finger print code////////////////////////////
int i = ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT);
boolean isFingerprintPermissionGranted = ActivityCompat.checkSelfPermission(
context, Manifest.permission.USE_FINGERPRINT)
== PackageManager.PERMISSION_GRANTED;
mFingerprintManager = FingerprintManagerCompat.from(getApplicationContext());
mFingerprintUiHelperBuilder = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManager); // FingerprintUiHelper
Log.i("CheckPermissionstate", "" + isFingerprintPermissionGranted);
if (isFingerprintPermissionGranted) {
if (!mFingerprintManager.isHardwareDetected()) {
Toast.makeText(this, "Your device does not support Finger Print",
Toast.LENGTH_LONG).show();
} else if (!mFingerprintManager.hasEnrolledFingerprints()) {
Toast.makeText(this, "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "you are good to go", Toast.LENGTH_LONG).show();
createKey();
check();
}
}
// ///////////////////////finger print code////////////////////////////
LayoutInflater layoutInflater = LayoutInflater.from(context);
View promptsView = layoutInflater.inflate(R.layout.popup_unlock, null);
Lock9View lock9View = (Lock9View) promptsView.findViewById(R.id.lock_9_view);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String pattern = sharedPreferences.getString("Password", "");
lock9View.setCallBack(new Lock9View.CallBack() {
#Override
public void onFinish(String password) {
if (password.matches(pattern)) {
dialog.dismiss();
AppLockLogEvents.logEvents(AppLockConstants.PASSWORD_CHECK_SCREEN, "Correct Password", "correct_password", "");
} else {
Toast.makeText(getApplicationContext(), "Wrong Pattern Try Again", Toast.LENGTH_SHORT).show();
AppLockLogEvents.logEvents(AppLockConstants.PASSWORD_CHECK_SCREEN, "Wrong Password", "wrong_password", "");
}
}
});
dialog = new Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
dialog.setContentView(promptsView);
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
///finger print method
private void check() {
boolean isFingerprintPermissionGranted = ActivityCompat.checkSelfPermission(
context, Manifest.permission.USE_FINGERPRINT)
== PackageManager.PERMISSION_GRANTED;
boolean isFingerprintAvailable = mFingerprintManager.isHardwareDetected()
&& mFingerprintManager.hasEnrolledFingerprints();
if (!isFingerprintPermissionGranted || !isFingerprintAvailable) {
} else if (initCipher()) {
setCryptoObject(new FingerprintManagerCompat.CryptoObject(mCipher));
FingerprintUiHelper.Callback callback = new FingerprintUiHelper.Callback() {
#Override
public void onAuthenticated() {
Log.i("checkauthenctication", "true");
}
#Override
public void onError() {
Log.i("checkauthenctication", "false");
}
};
mFingerprintUiHelper = mFingerprintUiHelperBuilder.build(
callback);
mFingerprintUiHelper.startListening(mCryptoObject);
if (mFingerprintUiHelper.isFingerprintAuthAvailable()) {
Log.i("checkavailability", "if");
} else {
Log.i("checkavailability", "else");
}
} else {
}
}
private void setCryptoObject(FingerprintManagerCompat.CryptoObject cryptoObject) {
mCryptoObject = cryptoObject;
}
#TargetApi(Build.VERSION_CODES.M)
private boolean initCipher() {
try {
if (mKeyStore == null) {
createKey();
}
mKeyStore.load(null);
SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
mCipher.init(Cipher.ENCRYPT_MODE, key);
return true;
} catch (KeyPermanentlyInvalidatedException e) {
return false;
} catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
| NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
throw new RuntimeException("Failed to init Cipher", e);
}
}
//create key for finger print
#TargetApi(Build.VERSION_CODES.M)
private void createKey() {
// The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
// for your flow. Use of keys is necessary if you need to know if the set of
// enrolled fingerprints has changed.
try {
mKeyStore = KeyStore.getInstance("AndroidKeyStore");
mKeyStore.load(null);
// Set the alias of the entry in Android KeyStore where the key will appear
// and the constrains (purposes) in the constructor of the Builder
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
// Require the user to authenticate with a fingerprint to authorize every use
// of the key
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException
| CertificateException | NoSuchProviderException | IOException e) {
throw new RuntimeException(e);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
}
return START_STICKY;
}
public boolean isConcernedAppIsInForeground() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> task = manager.getRunningTasks(5);
if (Build.VERSION.SDK_INT <= 20) {
if (task.size() > 0) {
ComponentName componentInfo = task.get(0).topActivity;
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (componentInfo.getPackageName().equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
} else {
String mpackageName = manager.getRunningAppProcesses().get(0).processName;
UsageStatsManager usage = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
mpackageName = "";
} else {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
}
for (int i = 0; pakageName != null && i < pakageName.size(); i++) {
if (mpackageName.equals(pakageName.get(i))) {
currentApp = pakageName.get(i);
return true;
}
}
}
return false;
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
timer = null;
if (imageView != null) {
windowManager.removeView(imageView);
}
try {
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}`enter code here`
Here are the links of classes that used in the above service.
FingerprintModule
FingerprintUiHelper
Because your service is running in the background.
When you start to listen the fingerprint.The FingerPrintServer will check your authority.
Here is the source code:
private boolean canUseFingerprint(String opPackageName, boolean foregroundOnly, int uid,int pid) {
checkPermission(USE_FINGERPRINT);
if (isKeyguard(opPackageName)) {
return true; // Keyguard is always allowed
}
if (!isCurrentUserOrProfile(UserHandle.getCallingUserId())) {
Slog.w(TAG,"Rejecting " + opPackageName + " ; not a current user or profile");
return false;
}
if (mAppOps.noteOp(AppOpsManager.OP_USE_FINGERPRINT, uid, opPackageName)
!= AppOpsManager.MODE_ALLOWED) {
Slog.w(TAG, "Rejecting " + opPackageName + " ; permission denied");
return false;
}
if (foregroundOnly && !isForegroundActivity(uid, pid)) {
Slog.w(TAG, "Rejecting " + opPackageName + " ; not in foreground");
return false;
}
return true;
}

Google Real-time Multiplayer on Android

I am having trouble with my app that uses Google's Real-time Multiplayer. When you launch the app, it just crashes. I added the crash log at the bottom...
I was able to find out that the problem was when I called mGoogleApiClient.connect();
Here is my code:
//(Your package here:)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.birdprograms.multiplayer.BaseGameUtils.src.main.java.com.google.example.games.basegameutils.BaseGameUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.GamesStatusCodes;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Participant;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
import com.google.android.gms.games.multiplayer.realtime.RealTimeMessageReceivedListener;
import com.google.android.gms.games.multiplayer.realtime.Room;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateListener;
import com.google.android.gms.games.multiplayer.realtime.RoomUpdateListener;
import com.google.android.gms.plus.Plus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener, RealTimeMessageReceivedListener, RoomUpdateListener, RoomStatusUpdateListener, OnInvitationReceivedListener{
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingConnectionFailure = false;
private boolean mSignInClicked = false;
private boolean mAutoStartSignInFlow = true;
String mRoomId = null;
ArrayList<Participant> mParrticipants = null;
String mMyId = null;
byte[] mMsgBuf = new byte[2];
private TextView textView;
private TextView myscoretxt;
private TextView urscoretxt;
final static int[] CLICKALBES = {
R.id.button,R.id.button2,R.id.button3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
for (int id : CLICKALBES){
findViewById(id).setOnClickListener(this);
}
}
private void startQuickGame(){
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS,0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
changedisplay(1);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
Games.RealTimeMultiplayer.create(mGoogleApiClient,rtmConfigBuilder.build());
}
#Override
public void onActivityResult(int requestCode, int responseCode,Intent intent){
super.onActivityResult(requestCode,responseCode,intent);
switch(requestCode){
case RC_SIGN_IN:
mSignInClicked = false;
mResolvingConnectionFailure = false;
if(responseCode == RESULT_OK){
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this, requestCode, requestCode, R.string.signin_other_error);
}
break;
};
super.onActivityResult(requestCode,responseCode,intent);
}
#Override
public void onStop(){
leaveRoom();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
changedisplay(0);
}
super.onStop();
}
#Override
public void onStart(){
changedisplay(0);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()){
} else {
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e){
if (keyCode == KeyEvent.KEYCODE_BACK && findViewById(R.id.button).getVisibility() == View.VISIBLE){
leaveRoom();
return true;
}
return super.onKeyDown(keyCode, e);
}
void leaveRoom(){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
resetGameVars();
if(mRoomId != null){
Games.RealTimeMultiplayer.leave(mGoogleApiClient, this, mRoomId);
mRoomId = null;
findViewById(R.id.button).setVisibility(View.VISIBLE);
changedisplay(0);
textView = (TextView)findViewById(R.id.textView3);
myscoretxt = (TextView)findViewById(R.id.textView);
urscoretxt = (TextView)findViewById(R.id.textView2);
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
mSignInClicked = true;
mGoogleApiClient.connect();
break;
case R.id.button2:
startQuickGame();
startGame(true);
break;
case R.id.button3:
scoreOnePoint();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure){
return;
}
if (mSignInClicked || mAutoStartSignInFlow){
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = BaseGameUtils.resolveConnectionFailure(this,mGoogleApiClient,connectionResult,RC_SIGN_IN,getString(R.string.signin_other_error));
}
changedisplay(1);
}
void updateRoom(Room room){
if(room != null){
mParrticipants = room.getParticipants();
}
if (mParrticipants != null){
updatePeerScoresDisplay();
}
}
#Override
public void onConnectedToRoom(Room room) {
mRoomId = room.getRoomId();
mParrticipants = room.getParticipants();
mMyId = room.getParticipantId(Games.Players.getCurrentPlayerId(mGoogleApiClient));
}
#Override
public void onDisconnectedFromRoom(Room room) {
mRoomId = null;
showGameError();
}
void showGameError(){
BaseGameUtils.makeSimpleDialog(this,getString(R.string.game_problem));
changedisplay(0);
}
#Override
public void onJoinedRoom(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
}
#Override
public void onRoomConnected(int i, Room room) {
if(i != GamesStatusCodes.STATUS_OK){
showGameError();
return;
}
updateRoom(room);
}
int mSecondsLeft = -1;
final static int GAME_DDURATION = 20;
int mScore = 0;
void resetGameVars(){
mSecondsLeft = GAME_DDURATION;
mScore = 0;
mParticipantScore.clear();
mFinishedParticipants.clear();
}
void startGame(boolean multiplayer){
updateScoreDisplay();
broadcastScore(false);
changedisplay(1);
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (mSecondsLeft <= 0)
return;
gameTick();
h.postDelayed(this, 1000);
}
}, 1000);
}
void gameTick(){
if(mSecondsLeft > 0)
--mSecondsLeft;
textView.setText("Time Left: "+mSecondsLeft+" seconds");
if (mSecondsLeft <= 0){
changedisplay(0);
broadcastScore(true);
}
}
void scoreOnePoint(){
if(mSecondsLeft <= 0)
return;
++mScore;
updateScoreDisplay();
updatePeerScoresDisplay();
broadcastScore(false);
}
Map<String, Integer> mParticipantScore = new HashMap<String, Integer>();
Set<String> mFinishedParticipants = new HashSet<String>();
#Override
public void onRealTimeMessageReceived(RealTimeMessage realTimeMessage) {
byte[] buf = realTimeMessage.getMessageData();
String sender = realTimeMessage.getSenderParticipantId();
if(buf[0] == 'F' || buf[0] == 'U'){
int existingScore = mParticipantScore.containsKey(sender) ?
mParticipantScore.get(sender) : 0;
int thisScore = (int) buf[1];
if(thisScore > existingScore){
mParticipantScore.put(sender, thisScore);
}
updatePeerScoresDisplay();
if((char) buf[0] == 'F'){
mFinishedParticipants.add(realTimeMessage.getSenderParticipantId());
}
}
}
void broadcastScore(boolean finalScore){
mMsgBuf[0] = (byte) (finalScore ? 'F' : 'U');
mMsgBuf[1] = (byte) mScore;
for(Participant p : mParrticipants){
if(p.getParticipantId().equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
if (finalScore){
Games.RealTimeMultiplayer.sendReliableMessage(mGoogleApiClient, null, mMsgBuf, mRoomId, p.getParticipantId());
} else {
Games.RealTimeMultiplayer.sendUnreliableMessage(mGoogleApiClient, mMsgBuf, mRoomId, p.getParticipantId());
}
}
}
void updateScoreDisplay(){
myscoretxt.setText("Your Score: "+fomatScore(mScore));
}
String fomatScore(int i){
if(i<0)
i=0;
String s = String.valueOf(i);
return s.length() == 1 ? "00" + s : s.length() == 2 ? "0" + s : s;
}
void updatePeerScoresDisplay(){
if(mRoomId != null){
for (Participant p : mParrticipants){
String pid = p.getParticipantId();
if(pid.equals(mMyId))
continue;
if (p.getStatus() != Participant.STATUS_JOINED)
continue;
int score = mParticipantScore.containsKey(pid) ? mParticipantScore.get(pid) : 0;
urscoretxt.setText("Opponents Score: "+fomatScore(score));
}
}
}
void changedisplay(int i){
if(i == 0){
findViewById(R.id.button).setVisibility(View.VISIBLE);
findViewById(R.id.button2).setVisibility(View.VISIBLE);
findViewById(R.id.button3).setVisibility(View.GONE);
findViewById(R.id.textView).setVisibility(View.GONE);
findViewById(R.id.textView2).setVisibility(View.GONE);
findViewById(R.id.textView3).setVisibility(View.GONE);
}
else{
findViewById(R.id.button).setVisibility(View.GONE);
findViewById(R.id.button2).setVisibility(View.GONE);
findViewById(R.id.button3).setVisibility(View.VISIBLE);
findViewById(R.id.textView).setVisibility(View.VISIBLE);
findViewById(R.id.textView2).setVisibility(View.VISIBLE);
findViewById(R.id.textView3).setVisibility(View.VISIBLE);
}
}
}
I have removed several callbacks for readers sake that did not cause the problem for sure!
If you read the whole thing, then thank you for your patience. :)
Any help, or suggestions would be helpful. Thanks!
-Nathan
Edit
Here is the crash log:
04-22 09:28:00.320 19247-19247/com.birdprograms.multiplayerdemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.birdprograms.multiplayerdemo, PID: 19247
java.lang.IllegalStateException: A fatal developer error has occurred. Check the logs for further information.
at com.google.android.gms.internal.jl$h.b(Unknown Source)
at com.google.android.gms.internal.jl$h.g(Unknown Source)
at com.google.android.gms.internal.jl$b.hy(Unknown Source)
at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5323)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
Your manifest is missing
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
// this is required if your RequestedClients is using AppStateManager.SCOPE_APP_STATE
<meta-data
android:name="com.google.android.gms.games.appstate.APP_ID"
android:value="#string/app_id" />

Categories

Resources