Android Webview signout issue - android-webview

In my webview app when I run the app for the first time and log out from a user session, close the app and then when I open the app again instead of asking user credentials I find myself already logged in. I tried clearing cookies but then it always require sign in on every restart. I only want it to ask for sign in when the user logs out from the app.
Please Help!!
Here is a snippet of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.framelayout);
bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setMax(100);
webview = (WebView) findViewById(R.id.mywebview);
webview.clearCache(true);
webview.clearHistory();
WebSettings mWebSettings = webview.getSettings();
mWebSettings.setSaveFormData(false);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webview = (WebView) findViewById(R.id.mywebview);
webview.setWebViewClient(new HelpClient());
webview.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(newProgress);
setTitle("Loading....");
if (newProgress == 100){
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, newProgress);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.setVerticalScrollBarEnabled(false);
webview.loadUrl(WebAddress);
webview.loadUrl("javascript:window.location.reload(true)");
swipe.setRefreshing(false);
bar.setProgress(0);
}
private class HelpClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
try {
webview.stopLoading();
} catch (Exception e) {
}
if (webview.canGoBack()) {
webview.goBack();
}
webview.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(view, request, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (webview.canGoBack()){
webview.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Run below code before loadUrl()
WebStorage webStorage = WebStorage.getInstance();
webStorage.deleteAllData();
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
I test it using Gmail account

CookieSynManager is now deprecated. This works for me :
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)

Related

Passing ExoPlayer instance from activity to binded service?

I'm trying to make a Video Player using ExoPlayer that can also work in the background and you can control it through the notification. I already created the ExoPlayer and the ForeGround Service for the notification and i binded them. At the moment it works as intended, the only problem is that i don't want the activity player to stop working when i close the notification. This happens because at the moment i'm creating the ExoPlayer instance in the service and then i pass the instance to the Activity, so when i close the notification the instance gets lost. Is there a way to initialize the player instance in the Activity and then pass that instance to the service so i can still control the video from the notification without risking to lose the instance once the notification is closed?
I'm pretty new to android and this is the first time that i'm binding a service to an activity so i don't really know how to do it. I tried searching on Google but that didn't help either.
This is the Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerView=findViewById(R.id.player_view);
intent=new Intent(this,AudioPlayerService.class);
//here i will add the url that needs to be loaded
//but at the moment this is just a draft
Util.startForegroundService(this,intent);
playerView.setUseController(true);
//playerView.showController();
playerView.setControllerAutoShow(true);
playerView.setControllerHideOnTouch(true);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
initializePlayer();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
public void onStart() {
super.onStart();
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
initializePlayer();
}
#Override
protected void onStop() {
unbindService(mConnection);
mBound = false;
super.onStop();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
private void initializePlayer() {
if (mBound) {
SimpleExoPlayer player = mService.getplayerInstance();
playerView.setPlayer(player);
}
}
}
This is the Service
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public SimpleExoPlayer getplayerInstance() {
if (player == null) {
startPlayer();
}
return player;
}
public class LocalBinder extends Binder {
public AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
final Context context=this;
}
private void startPlayer() {
final Context context = this;
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultHttpDataSourceFactory("NotificationSync", 10000, 10000, true))
.createMediaSource(Uri.parse("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, "1",
R.string.app_name,
2,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public String getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public String getCurrentContentText(Player player) {
return "text";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}, new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
mNotification = notification;
mNotificationId = notificationId;
if (ongoing) {
startForeground(notificationId, notification);
}
}
}
);
playerNotificationManager.setPlayer(player);
playerNotificationManager.setUseStopAction(true);
}
#Override
public void onDestroy() {
releasePlayer();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (player == null) {
//here i will get all the data from the intent that came from the
//activity (title,text,url...)
startPlayer();
}
return START_STICKY;
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
}
In the end all i want to achieve is a video player that you start in the activity and also works/can be controlled through a notification without interruption when i go from activity->background and background->activity. If there are other ways to achieve this i'm open to try.

Getting skipped frames with RxAndroid on a simple call

I'm implementing in a LauncherActivity (with just a loading indicator) an Observable (Single) from RxJava library to login with the previously recorded users credentials.
The activity is very very simple, and yet I get a skipped frames warning (40ish), both on my phone and on emulator, and I can't figure out why (though sometimes it doesn't show up).
Here is the code :
public class LauncherActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
if (UsersUtils.hasCredentialsRecorded(this)) {
getAccessToken();
} else {
login();
}
}
public void getAccessToken() {
Callable<Token> callable = new Callable<Token>() {
#Override
public Token call() throws Exception {
final Map<String, byte[]> credentials = UsersUtils.getCredentials(getApplicationContext());
Token token = OauthCalls.getToken(new String(credentials.get(UsersUtils.PREFERENCES_USER_KEY)),
new String(credentials.get(UsersUtils.PREFERENCES_PASS_KEY)));
return token;
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.subscribe(new DisposableSingleObserver<Token>() {
#Override
public void onSuccess(Token token) {
if (token == null) {
login();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onError(Throwable e) {
login();
}
});
}
public void login() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Thanks a lot for your help !

Deezer android sdk UI freeze during login

I implemented the Deeezer android SDK in my application and I got a user who can't log into its Deezer account on its Motorola Razr I. The login UI freezes on this page and the application restarts. He doesn't encounter the issue on its other devices.
The SDK version I use is 0.9.3
Here is a screenshot of the page where the application freezes.
What kind of information would help identify the issue?
Edit
Here is the source code :
public class LoginActivity extends Activity
{
protected static final String[] PERMISSIONS = new String[] {"basic_access", "manage_library", "delete_library", "listening_history", "manage_community"};
// DeezerConnect object
private DeezerConnect m_deezerConnect;
// Handle connection callbacks.
private DialogHandler m_dialogHandler = new DialogHandler();
// if the authentication failed, retry once
private boolean m_firstTry = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
m_deezerConnect = new DeezerConnectImpl(getString(R.string.deezer_app_id));
SessionStore sessionStore = new SessionStore();
AlertDialog.Builder deezerAuthDialog = new AlertDialog.Builder(this);
deezerAuthDialog.setTitle(R.string.deezer_authentication);
deezerAuthDialog.setMessage(R.string.enter_deezer_credentials);
deezerAuthDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
connectToDeezer(m_dialogHandler);
}
});
deezerAuthDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});
deezerAuthDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
finish();
}
});
deezerAuthDialog.show();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
/**
* Connects to Deezer web services using an injectable DialogListener listener.
* #param listener event listener that will be notified of the connection progress.
*/
private void connectToDeezer(final DialogListener listener)
{
m_deezerConnect.authorize(this, PERMISSIONS, listener);
}
/** Handle DeezerConnect callbacks. */
private class DialogHandler implements DialogListener
{
#Override
public void onComplete(final Bundle values)
{
SessionStore sessionStore = new SessionStore();
sessionStore.save(m_deezerConnect, LoginActivity.this);
LoginActivity.this.finish();
}
#Override
public void onDeezerError(final DeezerError deezerError)
{
Log.e(DeemoteGlobals.TAG, "DialogError error during login" , deezerError );
LoginActivity.this.finish();
}
#Override
public void onError(final DialogError dialogError)
{
// the api returns an error while the authentication succeed, so we force a retry once
int errorCode = dialogError.getErrorCode();
if (errorCode == -10 && m_firstTry)
{
m_firstTry = false;
connectToDeezer(m_dialogHandler);
return;
}
Log.e(DeemoteGlobals.TAG, "DialogError error during login", dialogError);
}
LoginActivity.this.finish();
}
#Override
public void onCancel()
{
LoginActivity.this.finish();
}
#Override
public void onOAuthException(OAuthException oAuthException)
{
LoginActivity.this.finish();
}
}
}

Progress Dialog on Rajawali Vuforia example

It is possible to show progress dialog when loading the .obj model. I tried to call the ProgressDialog in RajawaliVuforiaExampleRenderer.java but it said "Can't create handler inside thread that has not called Looper.prepare()"
I have pasted part of the code here:
protected void initScene() {
mLight = new DirectionalLight(.1f, 0, -1.0f);
mLight.setColor(1.0f, 0, 0);
mLight.setPower(1);
getCurrentScene().addLight(mLight);
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.wall_obj);
try {
// Load model
objParser.parse();
wall = objParser.getParsedObject();
addChild(wall);
} catch (Exception e) {
e.printStackTrace();
}
}
EDITED:
I have read the comment from Abhishek Agarwal and updated the code for Renderer part, now i having problem on calling the ProgressDialog when loading the model, here is my code for the UI thread.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// receive file path
String filePath = this.getIntent().getStringExtra("FullFilePath");
Log.i(filePath, "FullFilePath:" + filePath);
waitDialog = ProgressDialog.show(this, "", "Loading", true);
waitDialog.show();
new ModelLoader().execute();
}
#Override
protected void setupTracker() {
int result = initTracker(TRACKER_TYPE_MARKER);
if (result == 1) {
result = initTracker(TRACKER_TYPE_IMAGE);
if (result == 1) {
super.setupTracker();
} else {RajLog.e("Couldn't initialize image tracker.");
}
} else {
RajLog.e("Couldn't initialize marker tracker.");
}}
protected void initApplicationAR() {
super.initApplicationAR();
createImageMarker("marker.xml");
}
protected void initRajawali() {
super.initRajawali();
mRenderer = new ModelRenderer(this);
mRenderer.setSurfaceView(mSurfaceView);
super.setRenderer(mRenderer);
mUILayout = this;
mUILayout.setContentView(mLayout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
private class ModelLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
startVuforia();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
waitDialog.dismiss();
}
}
Progress Dialog can be shown on the UIThread. So show progress dialog on the main thread not under GLThread
You can use Handler to be on threadUI :
`private Handler mHandler = new Handler();
...
mHandler.post(new Runnable() {
#Override
public void run() {
view_progressBar.setProgress(val);
}
});`

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}