java.lang.IllegalStateException: AssetManager has been finalized - java

I went to sleep yesterday with my app working and today when I tried to run it won't start at all. As soon as I try to open it crashes with a java.lang.IllegalStateException. I've gone several commits back in my code just to rule out it was something I did recently and still. This makes no sense, how can an app just stop working over night? I've looked for the error in the internet and there is not a lot of useful information about it. Is this really an odd error?
Here's the complete stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: AssetManager has been finalized!
at android.os.Parcel.readException(Parcel.java:1439)
at android.os.Parcel.readException(Parcel.java:1385)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1947)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.app.Activity.startActivity(Activity.java:3583)
at com.android.launcher2.Launcher.startActivity(Launcher.java:2442)
at com.android.launcher2.Launcher.startActivitySafely(Launcher.java:2469)
at com.android.launcher2.AppsCustomizePagedView.onClick(AppsCustomizePagedView.java:584)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Since like I said it doesn't seem to be anything that I did I'm not sure what code to post. But given that the app crashes on start here's the code for the two main classes that are supposed to start first:
App
public class App extends Application {
private static App instance;
private static final String TAG = "Starter";
#Override
public void onCreate() {
super.onCreate();
instance = this;
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
//TODO: Register subclasses
// ParseObject.registerSubclass(Challenge.class);
//Parse server
Log.d(TAG, "Initializing Parse");
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(getString(R.string.parse_app_id))
.clientKey(getString(R.string.parse_client_key))
.server(getString(R.string.server_address)).build()
);
//Facebook
if (AccessToken.getCurrentAccessToken() == null)
ParseFacebookUtils.initialize(this);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Log.d(TAG, "Parse ready");
}
public static App getInstance(){
return instance;
}
}
SplashActivity
public class SplashActivity extends AppCompatActivity {
private static final String TAG = "Splash";
private boolean firstTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
firstTime = getSharedPreferences(Constants.GENERAL_SHARED_PREFS, MODE_PRIVATE)
.getBoolean(Constants.FIRSTTIME, true);
if (isLoggedIn())
if (firstTime)
startActivity(new Intent(SplashActivity.this, FirstTimeActivity.class));
else
startActivity(new Intent(SplashActivity.this, MenuActivity.class));
else {
Log.d(TAG, "Calling Home");
startActivity(new Intent(SplashActivity.this, WelcomeActivity.class));
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
String parseSession = ParseUser.getCurrentUser().getSessionToken();
return parseSession != null;
}
}

Your stacktrace links to this class in the AOSP.
I think this crash has nothing to do with your app, but as an error in the Launcher class. Try installing from USB debugging and see if that works.
But there are still some details that are blurry. These lines are (from bottom of the stacktrace to the top) the lines that cause problems in com.android.launcher2 package:
https://android.googlesource.com/platform/packages/apps/Launcher2/+/android-4.2.2_r1/src/com/android/launcher2/AppsCustomizePagedView.java#584
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2469
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2442
From this error, I assume you are using a Nexus or Pixel (or any device with the unaltered source code, meaning stock android.).
From what I can tell from this error, this is not an error related to your app. It appears to be an issue with the launcher you are using. Try installing from USB debugging, or change launcher, and see if that works. Try rebooting your device as well.
Further, from what I see of your code, there are no parcelable classes in use

This error can also be caused when Instant Run loses connection with the Android Emulator as a result of which new app changes are not persisted in the emulator.
Running the app again will solve the issue.

Related

App crash in Android Studio 4 emulator while testing recording and play

I've met with problems while testing a recording app on the emulator(Pixel 3a API 30)
Below is the Java code that I searched for in the tutorial on Youtube.
In the video it can be tested normally.
When it comes to me, it kept crashing when I hit on the stop recording button.
//Request Runtime Permission
if (!checkPermissionFromDevice())
requestPermission();
//Init view
pl_btn = (Button)findViewById(R.id.play_btn);
rcrd_btn = (Button)findViewById(R.id.record_button);
stp_rcrd_btn = (Button)findViewById(R.id.stop_record_btn);
ps_btn = (Button)findViewById(R.id.pause_btn);
//From Android M, need request Run-time permission
rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermissionFromDevice()) {
pathSave = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/"
+ UUID.randomUUID().toString() + "audio_record.3gp";
setupMediaRecorder();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
pl_btn.setEnabled(false);
ps_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
stp_rcrd_btn.setEnabled(true);
Toast.makeText(recording_and_play_test.this, "Recording...", Toast.LENGTH_SHORT).show();
} else {
requestPermission();
}
}
});
stp_rcrd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaRecorder.stop();
stp_rcrd_btn.setEnabled(false);
pl_btn.setEnabled(true);
rcrd_btn.setEnabled(true);
ps_btn.setEnabled(false);
}
});
pl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ps_btn.setEnabled(true);
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(false);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(pathSave);
mediaPlayer.prepare();
}catch (IOException e){
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(recording_and_play_test.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
ps_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stp_rcrd_btn.setEnabled(false);
rcrd_btn.setEnabled(true);
pl_btn.setEnabled(true);
ps_btn.setEnabled(false);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathSave);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
},REQUEST_PERMISSION_CODE);
}
And here's what the activity looks like
While I hit the stop recording button while executing the recording function, the app then just crashed and restarts again.
Here's what the build log says
E/MediaRecorder: stop called in an invalid state: 4
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.adrsingingscope, PID: 7309
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.adrsingingscope.recording_and_play_test$2.onClick(recording_and_play_test.java:88)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
This could be a problem with the path you created to save a file. These things can be easy to mess up. The media recorder has its own state and STATE 4 in which your app crashed in the state of recording. So it didn't stop and something happened in between that process so I assume it is related to saving your file to external storage.
You can find MEDIA_RECORDER_STATES here: https://android.googlesource.com/platform/frameworks/av/+/android-4.2.2_r1.2/include/media/mediarecorder.h#96
There are three things you can try.
Change your save file path
Try changing your path to a different directory. Sometimes you are trying to reach the directory you are not allowed to or it doesn't exist. More you can read in this answer: https://stackoverflow.com/a/33107120/14759470
Check your AndroidManifest.xml for permissions
Check if you wrote your permissions in AndroidManifest.xml as you should. You need WRITE_EXTERNAL_STORAGE and RECORD_AUDIO for this. In your code, it even says that from Android M (6.0) you need RUN_TIME permission. So just add them on top of your manifest file if you didn't.
Make your code better
Don't stop the recorder if it's already stopped. This will throw an exception. Don't release if already released, also an exception, and so on. So test your code for bugs, make breakpoints, and find your weak spots. It will be easier for you to find your errors. Also, check the log for more error messages since this one doesn't give us much.

Sinch Service not starting in Android

I was trying out the sample programs provided by Sinch and was getting a NullPointerException. I traced the code and found that it was caused by my device not connecting to the SinchService.
The code is as follows
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private Button mLoginButton;
private EditText mLoginName;
private ProgressDialog mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mLoginName = (EditText) findViewById(R.id.loginName);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setEnabled(false);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginClicked();
}
});
}
#Override
protected void onServiceConnected() {
mLoginButton.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
if (mSpinner != null) {
mSpinner.dismiss();
}
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
if (mSpinner != null) {
mSpinner.dismiss();
}
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
String userName = mLoginName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
showSpinner();
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(this, PlaceCallActivity.class);
startActivity(mainActivity);
}
private void showSpinner() {
mSpinner = new ProgressDialog(this);
mSpinner.setTitle("Logging in");
mSpinner.setMessage("Please wait...");
mSpinner.show();
}
}
I could see that since the service is not connecting I am not getting a correct output when I call getSinchServiceInterface(). It always returns null. My device is connected to the internet and the backend app in the Sinch dashboard seems to be working fine too.
LogCat:
12-22 17:43:38.432 2301-2301/com.login_signup_screendesign_demo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.login_signup_screendesign_demo, PID: 2301
java.lang.NullPointerException
at calling.LoginActivity.loginClicked(LoginActivity.java:78)
at calling.LoginActivity.access$000(LoginActivity.java:15)
at calling.LoginActivity$1.onClick(LoginActivity.java:32)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
What could be the cause of this error and how to solve it?
UPDATE:
I exactly copy pasted the android code downloaded from this page. I am using sinch-rtc-sample-calling app from that file. I compiled and ran the app separately and it was working fine. Then I copy pasted all the java and xml from that app into the one which I am working and it is not working. Why is this happening. This might be the reason for the NullPointerException. After copy pasting I found that the login button is disabled. That means the onServiceConnected() is not executing. I tried calling it manually and that is resulting in the NPE, but that is happening correctly in the standalone app. I am getting these kind of problems only upon integration.
PS : I updated the manifest and gradle as per the new files.
Have had the same issue over the past few days.
In my case it is because I hadn`t added the following in the manifest under application node
<service android:name=".SinchService"/>
Make sure that the setting is in your application manifest. That solved it for me.
everything looks fine, uncomment the commented part because there is one condition which is being checked and it returns
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
before getting SinchService and Also check your
private static final String APP_KEY = "app_key";
private static final String APP_SECRET = "app_secret";
private static final String ENVIRONMENT = "sandbox.sinch.com";
in SinchService.java, are the correct or not.

Start fragment in landscape mode

Thanks in advance for your help.
I'm trying to load one of my fragments which is loaded from a drawerlayout activity in landscape mode by invoking
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
The fragment does load in landscape mode. I also have a runnable thread which starts from onStart() after the fragment binds to a background service and the runnable is killed onStop().
private final Runnable initCommands = new Runnable() {
#Override
public void run() {
Log.d(TAG,"running thread");
if(isServiceBound) {
//some code...
new Handler().postDelayed(initCommands,800);
}
}
};
The runnable is launched after the fragment is bound to service:
private ServiceConnection serviceConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
ELMScanner.ELMScannerServiceBinder serviceBinder = (ELMScanner.ELMScannerServiceBinder) binder;
scanner = serviceBinder.getService();
isServiceBound = true;
if (scanner.isConnected()) {
Log.d(TAG,"init commands");
new Handler().post(initCommands);
}
}
public void onServiceDisconnected(ComponentName className) {
isServiceBound = false;
scanner.resetCommands();
}
};
#Override
public void onStop() {
super.onStop();
Log.d(TAG,"onStop");
FRAGMENT_RUNNING = 0;
if (isServiceBound) {
getActivity().getApplicationContext().unbindService(serviceConn);
Log.d(TAG,"unbinding service");
isServiceBound = false;
scanner.resetCommands();
}
}
The problem I'm facing is coming from setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE). For some reason this method reloads the fragment not killing the first thread and as a result there are two instances of the thread running.
07-30 18:38:53.054 2940-2940/com.package/FuelFragment﹕ on Attach
07-30 18:38:53.054 2940-2940/com.package/FuelFragment﹕ onCreate
07-30 18:38:53.054 2940-2940/com.package/FuelFragment﹕ onCreatView
07-30 18:38:53.054 2940-2940/com.package/FuelFragment﹕ onstart
07-30 18:38:53.062 2940-2940/com.package/FuelFragment﹕ onStop
07-30 18:38:53.062 2940-2940/com.package/FuelFragment﹕ on Detach
07-30 18:38:53.070 2940-2940/com.package/ApplicationPackageManager﹕ cscCountry is not German : THR
07-30 18:38:53.070 2940-2940/com.package/FuelFragment﹕ on Attach
07-30 18:38:53.070 2940-2940/com.package/FuelFragment﹕ onCreate
07-30 18:38:53.242 2940-2940/com.package/FuelFragment﹕ onCreatView
07-30 18:38:53.250 2940-2940/com.package/FuelFragment﹕ onstart
07-30 18:38:53.257 2940-2940/com.package/FuelFragment﹕ init commands
07-30 18:38:53.257 2940-2940/com.package/FuelFragment﹕ init commands
07-30 18:38:53.328 2940-2940/com.package/FuelFragment﹕ running thread
My question: is there an alternative to setRequestedOrientation() that does not reload fragment?
Thanks.
Solution:
In case you're wondering how to fix this.
In the method onStart(), add the condition
int orientation = getResources().getConfiguration().orientation;
if (orientation == 2) {
Intent serviceIntent = new Intent(getActivity(), ELMScanner.class);
getActivity().getApplicationContext().bindService(serviceIntent, serviceConn, Context.BIND_AUTO_CREATE);
}
This will ensure that the fragment only binds to service and runs the thread when it starts on landscape mode. Also make sure to add
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onDetach() {
super.onDetach();
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
AFAIK, no. Orientation changes need to restart the Activity/Fragment so the system gets a chance to reload all the resources.
From the docs for setRequestedOrientation:
Change the desired orientation of this activity. If the activity is
currently in the foreground or otherwise impacting the screen
orientation, the screen will immediately be changed (possibly causing
the activity to be restarted). Otherwise, this will be used the next
time the activity is visible.
Your code should be able to handle being destroyed and recreated without messing up and creating two threads. It's not clear what you're trying to accomplish so I can't give you any further suggestions, but properly handling the activity lifecycle is necessary.

Google+ sign in for android not working, error code 4

I have followed the guide on how to setup google+ sign in. I did every step and basically copy and pasted the code.
Here is the scenario. I develop on two different computers. I have two different client-ids in my console. One for computer A and one for computer B.
When i install the application and launch it, it will attempt to sign in and fail with the following error from logcat. If i back out of the app and re-launch, it will then sign in fine. When it fails, it will seem to be trying to launch an Activity but the Activity is never launched. Here is the logcat.
06-04 10:14:57.801 19948-19948/carbon.android.game.legions D/AccountFragment﹕ ResolveSignInError ErrorCode:4
06-04 10:14:57.801 602-823/? I/ActivityManager﹕ START u0 {cmp=com.google.android.gms/.plus.activity.AccountSignUpActivity (has extras)} from pid -1
06-04 10:14:57.811 178-646/? D/audio_hw_primary﹕ select_devices: out_snd_device(2: speaker) in_snd_device(0: )
06-04 10:14:57.811 178-646/? D/ACDB-LOADER﹕ ACDB -> send_afe_cal
06-04 10:14:57.821 602-2816/? I/ActivityManager﹕ START u0 {act=com.google.android.gms.common.account.CHOOSE_ACCOUNT pkg=com.google.android.gms cmp=com.google.android.gms/.common.account.AccountPickerActivity (has extras)} from pid 20027
06-04 10:14:57.941 20027-20031/? D/dalvikvm﹕ GC_CONCURRENT freed 601K, 7% free 9304K/9940K, paused 2ms+2ms, total 19ms
06-04 10:14:58.071 949-959/? W/GLSUser﹕ GoogleAccountDataService.getToken()
What am i doing wrong? I followed the guide word for word and basically copy and pasted the code. The only difference is that i am inside of a Fragment and not an Activity. But, that shouldn't matter.
Here is the code:
public class AccountFragment extends Fragment implements View.OnClickListener,
ConnectionCallbacks,
OnConnectionFailedListener {
private static final int RC_SIGN_IN = 1524;
private GoogleApiClient googleApiClient;
private boolean intentInProgress;
private boolean signInClicked;
private ConnectionResult connectionResult;
private SignInButton signInButton;
public AccountFragment() {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "The connection failed: " + connectionResult.getErrorCode());
if (!this.intentInProgress) {
this.connectionResult = connectionResult;
if (this.signInClicked) {
this.resolveSignInError();
}
}
}
#Override
public void onStart() {
super.onStart();
this.googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (this.googleApiClient.isConnected()) {
this.googleApiClient.disconnect();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.googleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
if (!this.googleApiClient.isConnecting() && !this.googleApiClient.isConnected()) {
this.signInClicked = true;
this.resolveSignInError();
} else {
Log.d(TAG, "OnClick else");
}
break;
default:
break;
}
}
#Override
public void onConnected(Bundle bundle) {
this.signInClicked = false;
Person currentPerson = Plus.PeopleApi.getCurrentPerson(this.googleApiClient);
Log.d(TAG, "User connected: " + currentPerson.getDisplayName());
Log.d(TAG, "User id: " + currentPerson.getId());
Toast.makeText(this.getActivity(), "User connected: " + currentPerson.getDisplayName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
this.googleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
if (resultCode != Activity.RESULT_OK) {
this.signInClicked = false;
}
this.intentInProgress = false;
if (!this.googleApiClient.isConnecting()) {
this.googleApiClient.connect();
}
}
}
private void resolveSignInError() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity()) != ConnectionResult.SUCCESS) {
Log.e(TAG, "Google Play Services is not available.");
}
Log.d(TAG, "ResolveSignInError ErrorCode:" + this.connectionResult.getErrorCode());
if (this.connectionResult.hasResolution()) {
this.intentInProgress = true;
try {
this.connectionResult.startResolutionForResult(this.getActivity(), RC_SIGN_IN);
} catch (SendIntentException e) {
e.printStackTrace();
this.intentInProgress = false;
this.googleApiClient.connect();
}
}
}
}
I figured out my issue.
There were a couple of issues.
With all my testing, i have been attempting to sign in the whole time. And was successful sometimes. Somehow, i was remaining authenticated even though my app was not signed in. I added the ability to sign out and revoke access. After revoking access and attempting to sign in again, the Activity would launch to resolve any errors.
I was also having the issue that is being discussed here. My host Activity was consuming my onActivityResult(...) from my connectionResult.startResolutionForResult(...);. So, after some trial and error i finally found a solution to that issue as well. The question linked helped but did not fully solve the issue. Please view my answer to that question for how i solved the problem.
Lesson, make sure that you are signing out and revoking access while testing. If you are having these issues, try revoking access and then signing back in.
In my case i solve my problem by doing following step, its old que but others my also having this problem so
Follow these stem in android development Console
Open the Credentials page.
Click Add credentials > OAuth 2.0 client ID.
Select Android.
and fill the fingerprint and package name .
Click Create.
Then there will be successful sing in from google.
Hope this may solve your problem. !!!
Please msg me if any problem occurs.

Android Services

I'm writing a web server for android. Actually it works with threads, but now I would use a service to make it running in background. I replaced the thread with a service, but I don't know if this design is ok...
When I press a button it starts then it stays in listening. When there is a request, the service create a thread to serve it.
This is my structure:
WebServer.java
class WebServer extends Service{
onCreate(){...}
onDestroy(){...}
}
DroidServer.java
class DroidServer extends WebServer{...}
MyActivity.java
MyActivity extends Activity{
boolean isOn=false;
btn.setOnClickListener(new OnClickListener(){
public void onClick(View V){
if(!isOn){
startService(new Intent(this, DroidWebServer.class));
btn.setText("Stop");
}else{
stopService(new Intent(this, DroidWebServer.class));
btn.setText("Start");
}}});
}
AndroidManifest.xml
... <service android:name='DroidWebServer'/> ...
But when I click on the button I get this exception:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to Instantiate service it.giox.ws.DroidWebServer: java.lang.InstantiationException: it.giox.ws.DroidWebServer
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1933)
at android.app.ActivityThread.access$2500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3729)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: it.giox.ws.DroidWebServer
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1409)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1930)
... 10 more
Where's the problem?
Have you seen this post? It basically says there is an error in your constructor. His fix was to remove the argument, and also make sure to call the super's constructor ...
InstantiationException occurs when an exception is thrown out of a
constructor. Generally there should be another exception reported as
causing the InstantiationException, and the stack trace should point
to the specific lines that are in error. Stack trace is your friend,
and you should be grateful -- their are poor children programming on
Symbian devices who have no stack trace.
Did you implement the callback method onStartCommand() in your subclass (either WerServer or DroidServer)? Check out Service.startService() for details.
Personally, I think use the bound form of service is more reasonable in your design, where you can replace a is-a relationship with a has-a relationship.
Your WebServer:
class WebServer implements IWebServer {
doSoming();
}
Your DroidServer:
class DroidServer extends Service {
private WebServer webServer;
private WebServerBinder myBinder;
onCreate(){...}
IBinder onBind(Intent intent) {
return myBinder;
}
onDestroy(){...}
protected class WebServerBinder extends Binder implements IWebServer {
doSomething() {
myServer.doSomething();
}
}
}
In your Activity, use your DroidServer like this:
public class MyActivity extends Activity {
private IWebServer myWebService;
private ServiceConnection myServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myWebService = (IWebServer) service;
}
public void onServiceDisconnected(ComponentName className) {
if (myWebService != null)
myWebService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(this, DroidWebServer.class),
myServiceConnection, Context.BIND_AUTO_CREATE);
boolean isOn=false;
btn.setOnClickListener(new OnClickListener(){
public void onClick(View V){
if(!isOn){
myWebService.doSomething();
btn.setText("Stop");
}else{
myWebService.doSomethingElse(someParam);
btn.setText("Start");
}}});
}
#Override
public void onDestroy() {
super.onDestroy();
unbindService(myServiceConnection );
}
}

Categories