attempting to clean up some outdated twitter authentication code Ive been using as the newer versions of android do not allow for network tasks to be done on the ui thread anymore without crashing the app.
I seemed to of solved half the problem by sticking the webview.loadurl(); call onto an async task but the app then crashes during the second part of the process when onLoadResource(); is called by the webviewclient, just cant figure out what the best way would be to place the onLoadResource(); method into an async task without breaking the code.
package com.testapp2.second.activities;
import com.testapp2.second.OTweetApplication;
import com.testapp2.second.R;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class AuthorizationActivity extends Activity {
private OTweetApplication app;
private WebView webView;
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
// the URL we're looking for looks like this:
// http://otweet.com/authenticated?oauth_token=1234567890qwertyuiop
Uri uri = Uri.parse(url);
if (uri.getHost().equals("otweet.com")) {
String token = uri.getQueryParameter("oauth_token");
if (null != token) {
webView.setVisibility(View.INVISIBLE);
app.authorized();
finish();
} else {
// tell user to try again
}
} else {
super.onLoadResource(view, url);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (OTweetApplication)getApplication();
setContentView(R.layout.authorization_view);
setUpViews();
}
#Override
protected void onResume() {
super.onResume();
new AuthInBg().execute();
}
private void setUpViews() {
webView = (WebView)findViewById(R.id.web_view);
webView.setWebViewClient(webViewClient);
}
private class AuthInBg extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
String authURL = app.beginAuthorization();
webView.loadUrl(authURL);
return null;
}
}
}
should I change the async task result to a constructor for the OnLoadResource(); method perhaps?
I think that you need to put in runOnUIThread() method the webView.setVisibility(View.INVISIBLE); line and it should work.
it should be like this:
runOnUiThread(new Runnable() {
public void run() {
webView.setVisibility(View.INVISIBLE);
}
});
Related
I'm trying to use AsyncTask to make HTTP GET requests in Android Studio. This AsyncTask class is used across many activities of the app. I want to assign a void function to the AsyncTask which will execute after the doInBackground has fetched the HTTP GET request. The HTTP returned response should be inserted into the void's parameter. I have researched a lot of times but cannot find a simple working solution. Need Help. Thanks.
Main.java containing the AsyncTask class:
package com.example.NAME;
import android.os.AsyncTask;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static class GetData extends AsyncTask<String, Void, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
}
}
}
Activity1.java using the AsyncTask class:
package com.example.NAME;
import android.app.Activity;
import android.os.Bundle;
public class Activity1 extends Activity {
private final Main main = new Main();
#Override
protected synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity1);
}
public synchronized void GET_Request(View v) {
Main.GetData t = new Main.GetData();
t.execute("STRING");
/*
How to attach the `after_GET_Request` void that should be executed
after the HTTP GET Request happens and should receive the returned
Boolean value.
*/
}
public synchronized void after_GET_Request(Boolean b) {
// Use the Boolean data received from AsyncTask.
}
}
Add a result callback to your AsyncTask and process the outcome:
public static class GetData extends AsyncTask<String, Void, Boolean> {
private ResultCallback mCallback;
public GetData(ResultCallback callback) {
mCallback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
mCallback.onResultReady(_return);
}
public interface ResultCallback {
void onResultReady(Boolean result);
}
}
And then in your activity call your function:
Main.GetData t = new Main.GetData(new ResultCallback() {
#Override
public void onResultReady(Boolean result) {
after_GET_Request(result);
}
});
t.execute("STRING");
I'm doing a project with ibeacon using Eclipse to build an APP , I import some codes from Android beacon library for detecting UUID , with no error in the codes , I try to open the apk on HTC device, but failed to open the App .
Here is my code. Any help or suggest is appreciated.
package com.example.goooooood;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.Region;
import android.app.Activity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public abstract class MainActivity extends Activity implements BeaconConsumer {
protected static final String TAG = "MonitoringActivity";
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.i(TAG, "I just saw an beacon for the first time!");
}
#Override
public void didExitRegion(Region region) {
Log.i(TAG, "I no longer see an beacon");
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
} catch (RemoteException e) { }
}}
Here is the logcat.
logat part 1 of the code
logcat part 2 of the code
package fr.pchab.AndroidRTC;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;
import org.json.JSONException;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.VideoRenderer;
import java.util.List;
public class RTCActivity extends Activity implements WebRtcClient.RTCListener{
private final static int VIDEO_CALL_SENT = 666;
private VideoStreamsView vsv;
private WebRtcClient client;
private String mSocketAddress;
private String callerId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
mSocketAddress = "http://" + getResources().getString(R.string.host);
mSocketAddress += (":"+getResources().getString(R.string.port)+"/");
PeerConnectionFactory.initializeAndroidGlobals(this);
// Camera display view
Point displaySize = new Point();
getWindowManager().getDefaultDisplay().getSize(displaySize);
vsv = new VideoStreamsView(this, displaySize);
client = new WebRtcClient(this, mSocketAddress);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
final List<String> segments = intent.getData().getPathSegments();
callerId = segments.get(0);
}
}
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onPause() {
super.onPause();
vsv.onPause();
}
#Override
public void onResume() {
super.onResume();
vsv.onResume();
}
#Override
public void onCallReady(String callId) {
if(callerId != null) {
try {
answer(callerId);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
call(callId);
}
}
public void answer(String callerId) throws JSONException {
client.sendMessage(callerId, "init", null);
startCam();
}
public void call(String callId) {
Intent msg = new Intent(Intent.ACTION_SEND);
msg.putExtra(Intent.EXTRA_TEXT, mSocketAddress + callId);
msg.setType("text/plain");
startActivityForResult(Intent.createChooser(msg, "Call someone :"), VIDEO_CALL_SENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == VIDEO_CALL_SENT) {
startCam();
}
}
public void startCam() {
setContentView(vsv);
// Camera settings
client.setCamera("front", "640", "480");
client.start("android_test", true);
}
#Override
public void onStatusChanged(final String newStatus) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), newStatus, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLocalStream(MediaStream localStream) {
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(new VideoCallbacks(vsv, 0)));
}
#Override
public void onAddRemoteStream(MediaStream remoteStream, int endPoint) {
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(new VideoCallbacks(vsv, endPoint)));
vsv.shouldDraw[endPoint] = true;
}
#Override
public void onRemoveRemoteStream(MediaStream remoteStream, int endPoint) {
remoteStream.videoTracks.get(0).dispose();
vsv.shouldDraw[endPoint] = false;
}
// Implementation detail: bridge the VideoRenderer.Callbacks interface to the
// VideoStreamsView implementation.
private class VideoCallbacks implements VideoRenderer.Callbacks {
private final VideoStreamsView view;
private final int stream;
public VideoCallbacks(VideoStreamsView view, int stream) {
this.view = view;
this.stream = stream;
}
#Override
public void setSize(final int width, final int height) {
view.queueEvent(new Runnable() {
public void run() {
view.setSize(stream, width, height);
}
});
}
#Override
public void renderFrame(VideoRenderer.I420Frame frame) {
view.queueFrame(stream, frame);
}
}
}
I want to use webrtc in my android app.
https://github.com/pchab/AndroidRTC
after import project from this site video calling or voice calling or chatting is not working.
how can i use websocket library send data and receive for video or voice chatting?
can we interface WEBRTC API with webview.
or how can we do voice chatting and display view in chrom in any control of android.
now i am using webrtc in a native app but it is not working.
if u have any other code or project for webrtc in android than send me link.
I want to use webrtc in my android app.
https://github.com/pchab/AndroidRTC
after import project from this site video calling or voice calling or chatting is not working.
how can i use websocket library send data and receive for video or voice chatting?
can we interface WEBRTC API with webview.
To get this application working you need a server-side which will do the signaling job. If you don't want to develope yourself you can install the node.js server with its desktop client from the same project (just follow How To instructions from AndroidRTC and the Install instructions from ProjectRTC):
https://github.com/pchab/ProjectRTC
Hope it helps.
Hi I have created download process activity and it's run on button click. This activity opens on listitem click. But Now I want to run the download process on lisitem click, instread of button click.
ZipDownloader.java
import java.io.File;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.kabelash.sg.util.DecompressZip;
import com.kabelash.sg.util.DownloadFile;
import com.kabelash.sg.util.ExternalStorage;
import com.kabelash.sg.R;
public class ZipDownloader extends Activity {
protected ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.zipdownload );
// Keep the screen (and device) active as long as this app is frontmost.
// This is to avoid going to sleep during the download.
getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
}
/**
* Invoked when user presses "Start download" button.
*/
public void startDownload( View v ) {
String url = "http://sample.co.uk/sample.zip";
new DownloadTask().execute( url );
}
/**
* Background task to download and unpack .zip file in background.
*/
private class DownloadTask extends AsyncTask<String,Void,Exception> {
#Override
protected void onPreExecute() {
showProgress();
}
#Override
protected Exception doInBackground(String... params) {
String url = (String) params[0];
try {
downloadAllAssets(url);
} catch ( Exception e ) { return e; }
return null;
}
}
//Progress window
protected void showProgress( ) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle( R.string.progress_title );
mProgressDialog.setMessage( getString(R.string.progress_detail) );
mProgressDialog.setIndeterminate( true );
mProgressDialog.setCancelable( false );
mProgressDialog.show();
}
protected void dismissProgress() {
// You can't be too careful.
if (mProgressDialog != null && mProgressDialog.isShowing() && mProgressDialog.getWindow() != null) {
try {
mProgressDialog.dismiss();
} catch ( IllegalArgumentException ignore ) { ; }
}
mProgressDialog = null;
}
}
on MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.update:
Intent intent = new Intent(this, ZipDownloader.class);
startActivity(intent);
break;
}
return true;
}
Please don't ignore this question. Thanks in advance and sorry for my English.
Have you tried bringing your AsyncTask code into the activity you want your listitem clicked, then just
switch(item.getItemId()){
case R.id.update:
String url = "http://sample.co.uk/sample.zip";
new DownloadTask().execute( url );
break;
}
return true;
call the background task onclick?
I have 300 MB videos on my http server...I'm trying to make good simple code to play (in 3G mode) these videos remotely in my application - sd storing or local storing is not a option. Of course I started from demo source in SDK android-17 (MediaPlayerDemo_Video, VideoViewDemo...) and in 3G mode my video doesn't play (I'm testing on Samsung Galaxy Nexus). After that I made new try in next code:
/**
* Listing 15-4: Initializing and assigning a Surface View to a Media Player
*/
import java.io.IOException;
import mobile.dariknews.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
public class SurfaceViewVideoViewActivity extends Activity
implements SurfaceHolder.Callback {
static final String TAG = "SurfaceViewVideoViewActivity";
private MediaPlayer mediaPlayer;
public void surfaceCreated(SurfaceHolder holder) {
try {
// When the surface is created, assign it as the
// display surface and assign and prepare a data
// source.
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("http://snimkitevi-bg.com/darik/1.MP4");
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
Log.e(TAG, "Illegal Argument Exception", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Illegal State Exception", e);
} catch (SecurityException e) {
Log.e(TAG, "Security Exception", e);
} catch (Exception e) {
Log.e(TAG, "IO Exception", e);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceviewvideoviewer);
// Create a new Media Player.
mediaPlayer = new MediaPlayer();
// Get a reference to the Surface View.
final SurfaceView surfaceView =
(SurfaceView)findViewById(R.id.surfaceView);
// Configure the Surface View.
surfaceView.setKeepScreenOn(true);
// Configure the Surface Holder and register the callback.
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
// Connect a play button.
Button playButton = (Button)findViewById(R.id.buttonPlay);
playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.start();
}
});
// Connect a pause button.
Button pauseButton = (Button)findViewById(R.id.buttonPause);
pauseButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.pause();
}
});
// Add a skip button.
Button skipButton = (Button)findViewById(R.id.buttonSkip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.seekTo(mediaPlayer.getDuration()/2);
}
});
/**
* Listing 15-5: Controlling playback using the Media Controller
*/
MediaController mediaController = new MediaController(this);
mediaController.setMediaPlayer(new MediaPlayerControl() {
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
public void start() {
mediaPlayer.start();
}
});
}
}
after that new try in
import android.app.Activity;
import android.app.Application;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.widget.MediaController;
import android.widget.VideoView;
public class PlayerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoplayer);
new LoadOutbox().execute();
}
/**
* Background Async Task to Load all OUTBOX messages by making HTTP Request
* */
class LoadOutbox extends AsyncTask<String, String, String> {
int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Outbox JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
VideoView videoView = (VideoView) findViewById(R.id.videoView1);
videoView.setKeepScreenOn(true);
// Attach a Media Controller MediaController mediaController = new
// MediaController( this); videoView.setMediaController(
// mediaController);
MediaController mediaController = new MediaController(
PlayerActivity.this);
videoView.setMediaController(mediaController);
Uri uri = Uri.parse("http://snimkitevi-bg.com/darik/1.MP4");
videoView.setVideoURI(uri);
videoView.start();
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public static Bitmap getLocalImageBitmap(String url) {
return MainNewsActivities.getLocalImageBitmap(url);
}
}
After that I played with 50 other tests with MediaPlayer and VIewVideo... All results are same - slow and freezed video playing. My need is pretty simple - I have big video files (mp4) on my website and I want to play them on my app. So I'm here - what is the right formula for playing of large remote files in android application?
PS: Of course I tried to use GStreamer but this framework is not compatible with last android environment - I played with in 2 days...My video is OK - in wifi mode I play http://snimkitevi-bg.com/darik/1.MP4
So could you give me some good advases, examples, tutorials how MediaPlayer could play normally, buffered and fastly big video files in 3G internet connection?