I am using following class to open a link in child browser , but unable to track device back button event on Android.
I am using showWebPage method, As there is also close button but i want to track device back button event.
public class ChildBrowser extends Plugin {
protected static final String LOG_TAG = "ChildBrowser";
private static int CLOSE_EVENT = 0;
private static int LOCATION_CHANGED_EVENT = 1;
private String browserCallbackId = null;
private Dialog dialog;
private WebView webview;
private EditText edittext;
private boolean showLocationBar = true;
/**
* Executes the request and returns PluginResult.
*
* #param action The action to execute.
* #param args JSONArry of arguments for the plugin.
* #param callbackId The callback id used when calling back into JavaScript.
* #return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("showWebPage")) {
this.browserCallbackId = callbackId;
// If the ChildBrowser is already open then throw an error
if (dialog != null && dialog.isShowing()) {
return new PluginResult(PluginResult.Status.ERROR, "ChildBrowser is already open");
}
result = this.showWebPage(args.getString(0), args.optJSONObject(1));
if (result.length() > 0) {
status = PluginResult.Status.ERROR;
return new PluginResult(status, result);
} else {
PluginResult pluginResult = new PluginResult(status, result);
pluginResult.setKeepCallback(true);
return pluginResult;
}
}
else if (action.equals("close")) {
closeDialog();
JSONObject obj = new JSONObject();
obj.put("type", CLOSE_EVENT);
PluginResult pluginResult = new PluginResult(status, obj);
pluginResult.setKeepCallback(false);
return pluginResult;
}
else if (action.equals("openExternal")) {
result = this.openExternal(args.getString(0), args.optBoolean(1));
if (result.length() > 0) {
status = PluginResult.Status.ERROR;
}
}
else {
status = PluginResult.Status.INVALID_ACTION;
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Display a new browser with the specified URL.
*
* #param url The url to load.
* #param usePhoneGap Load url in PhoneGap webview
* #return "" if ok, or error message.
*/
public String openExternal(String url, boolean usePhoneGap) {
try {
Intent intent = null;
if (usePhoneGap) {
intent = new Intent().setClass(this.ctx.getContext(), org.apache.cordova.DroidGap.class);
intent.setData(Uri.parse(url)); // This line will be removed in future.
intent.putExtra("url", url);
// Timeout parameter: 60 sec max - May be less if http device timeout is less.
intent.putExtra("loadUrlTimeoutValue", 60000);
// These parameters can be configured if you want to show the loading dialog
intent.putExtra("loadingDialog", "Wait,Loading web page..."); // show loading dialog
intent.putExtra("hideLoadingDialogOnPageLoad", true); // hide it once page has completely loaded
}
else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
}
this.ctx.startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
Log.d(LOG_TAG, "ChildBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
private void closeDialog() {
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.webview.canGoBack()) {
this.webview.goBack();
}
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.webview.canGoForward()) {
this.webview.goForward();
}
}
/**
* Navigate to the new page
*
* #param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.webview.loadUrl("http://" + url);
} else {
this.webview.loadUrl(url);
}
this.webview.requestFocus();
}
/**
* Should we show the location bar?
*
* #return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
/**
* Display a new browser with the specified URL.
*
* #param url The url to load.
* #param jsonObject
*/
public String showWebPage(final String url, JSONObject options) {
// Determine if we should hide the location bar.
if (options != null) {
showLocationBar = options.optBoolean("showLocationBar", true);
}
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* #return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
ctx.getContext().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(ctx.getContext(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", CLOSE_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(ctx.getContext());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(ctx.getContext());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(ctx.getContext());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
ImageButton back = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
try {
back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
try {
forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(ctx.getContext());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
ImageButton close = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
try {
close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
webview = new WebView(ctx.getContext());
webview.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
webview.setWebChromeClient(new WebChromeClient());
WebViewClient client = new ChildBrowserClient(edittext);
webview.setWebViewClient(client);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
settings.setPluginsEnabled(true);
settings.setDomStorageEnabled(true);
webview.loadUrl(url);
webview.setId(6);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.requestFocus();
webview.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(webview);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.FILL_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private Bitmap loadDrawable(String filename) throws java.io.IOException {
InputStream input = ctx.getAssets().open(filename);
return BitmapFactory.decodeStream(input);
}
};
this.ctx.runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin result and send it back to JavaScript
*
* #param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
if (this.browserCallbackId != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
result.setKeepCallback(keepCallback);
this.success(result, this.browserCallbackId);
}
}
/**
* The webview client receives notifications about appView
*/
public class ChildBrowserClient extends WebViewClient {
EditText edittext;
/**
* Constructor.
*
* #param mContext
* #param edittext
*/
public ChildBrowserClient(EditText mEditText) {
this.edittext = mEditText;
}
/**
* Notify the host application that a page has started loading.
*
* #param view The webview initiating the callback.
* #param url The url of the page.
*/
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc;
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
} else {
newloc = "http://" + url;
}
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOCATION_CHANGED_EVENT);
obj.put("location", url);
sendUpdate(obj, true);
} catch (JSONException e) {
Log.d("ChildBrowser", "This should never happen");
}
}
}
}
Related
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte
private TextView textStreamed;
private ImageView playButton;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context, TextView textStreamed,
ImageView playButton, ProgressBar progressBar) {
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
}
/**
* Progressivly download the media to a temporary location and update the
* MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(),
"Unable to initialize the MediaPlayer for fileUrl="
+ mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
/**
* Download the url stream to a temporary location and then call the
* setDataSource for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(),
"Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),
"downloadingMedia.dat");
// Just in case a prior deletion failed because our code crashed or
// something, we also delete any previously
// downloaded file to ensure we start fresh. If you use this code,
// always delete
// no longer used downloads else you'll quickly fill up your hard disk
// memory. Of course, you can also
// store any previously downloaded file in a separate data cache for
// instant replay if you wanted as well.
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead / 1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// mediaPlayer.release();
}
return false;
} else {
return true;
}
}
/**
* Test whether we need to transfer buffered data to the MediaPlayer.
* Interacting with MediaPlayer on non-main UI thread can causes crashes to
* so perform this using a Handler.
*/
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum
// buffered data
if (totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error copying buffered conent.", e);
}
}
} else if (mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000) {
// NOTE: The media player has stopped at the end so transfer
// any existing buffered data
// We test for < 1second of data because the media player
// can stop when there is still
// a few milliseconds of data left to play
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// We double buffer the data to avoid potential read/write errors
// that could happen if the
// download thread attempted to write at the same time the
// MediaPlayer was trying to read.
// For example, we can't guarantee that the MediaPlayer won't open a
// file for playing and leave it locked while
// the media is playing. This would permanently deadlock the file
// download. To avoid such a deadloack,
// we move the currently loaded data to a temporary buffer file that
// we start playing while the remaining
// data downloads.
moveFile(downloadingMediaFile, bufferedFile);
Log.e(getClass().getName(),
"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),
"Buffered File length: " + bufferedFile.length() + "");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so
// update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
/**
* Transfer buffered data to the MediaPlayer. NOTE: Interacting with a
* MediaPlayer on a non-main UI thread can cause thread-lock and crashes so
* this method should always be called using a Handler.
*/
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after
// transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File.
// Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),
"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on
// exit. If it's already deleted, then this won't mean anything. If
// you want to
// keep and track fully downloaded files for later use, write
// caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile, bufferedFile);
// Pause the current player now as we are about to create and start
// a new one. So far (Android v1.5),
// this always happens so quickly that the user never realized we've
// stopped the player and started a new one
mediaPlayer.pause();
// Create a new MediaPlayer rather than try to re-prepare the prior
// one.
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
// Restart if at end of prior buffered content or mediaPlayer was
// previously playing.
// NOTE: We test for < 1second of data because the media player can
// stop when there is still
// a few milliseconds of data left to play
boolean atEndOfFile = mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mediaPlayer.start();
}
// Lastly delete the previously playing buffered File as it's no
// longer needed.
oldBufferedFile.delete();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + "Kb"));
float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
progressBar.setSecondaryProgress((int) (loadProgress * 100));
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to
// the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed
.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
progressBar.setProgress((int) (progress * 100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
/**
* Move the file in oldLocation to newLocation.
*/
public void moveFile(File oldLocation, File newLocation) throws IOException {
if (oldLocation.exists()) {
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(oldLocation));
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(newLocation, false));
try {
// byte[] buff = new byte[8192];
/* changing the size of the buffer */
byte[] buff = new byte[16384];
int numChars;
while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
writer.write(buff, 0, numChars);
}
} catch (IOException ex) {
throw new IOException("IOException when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
} finally {
try {
if (reader != null) {
writer.close();
reader.close();
}
} catch (IOException ex) {
Log.e(getClass().getName(),
"Error closing files when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
} else {
throw new IOException(
"Old location does not exist when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
public void change_volume(float vol) {
Log.i("Media Player volume change", "Success" + vol);
mediaPlayer.setVolume(vol, vol);
}
public void stop() {
// TODO Auto-generated method stub
mediaPlayer.stop();
}
public void stoppreviousPlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer.release();
}
}
}
second class ------------------------------------------------------------
public class Play_Radio extends Activity
{
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
public static String name, rating, like, radio_url, id, listner, image;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.play_radio);
/*
* LayoutInflater li = getLayoutInflater(); View layout =
* li.inflate(R.layout.customtoast, (ViewGroup)
* findViewById(R.id.custom_toast_layout)); Toast toast = new
* Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_LONG);
* toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
* toast.setView(layout); toast.show();
*/
// AdRequest adRequest = new AdRequest();
// adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
// adView = (AdView)findViewById(R.id.adView);
//
// For listner count
/*
*
* HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost =
* new HttpPost(
* "http://vaibhavtech.com/work/android/radio_listner.php"); try { //
* Add your data List<NameValuePair> nameValuePairs = new
* ArrayList<NameValuePair>(1); nameValuePairs.add(new
* BasicNameValuePair("id", Tab_Listner.id)); httppost.setEntity(new
* UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String>
* responseHandler = new BasicResponseHandler(); String response =
* httpclient.execute(httppost, responseHandler);
*
* // This is the response from a php application String reverseString =
* response; Log.i("response", reverseString);
*
* } catch (ClientProtocolException e) { Log.i("CPE response ",
* e.toString()); // TODO Auto-generated catch block } catch
* (IOException e) { Log.i("IOException response ", e.toString()); //
* TODO Auto-generated catch block }
*/
if (audioStreamer != null) {
try {
Log.i("Already ply", "Succss");
audioStreamer.stop();
} catch (Exception e) {
}
} else {
Log.i("First time", "Play");
}
initControls();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("On Pause is call", "Succcess");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
Log.i("Android Device above", "Home Enbled");
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
// protected void onDestroy()
// {
// super.onDestroy();
//
//
// if ( audioStreamer != null)
// { audioStreamer.interrupt();
// }
//
// }
private void initControls() {
iv_like = (ImageView) findViewById(R.id.iv_activity_like);
iv_like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
Toast.makeText(getApplicationContext(),
"Thanks For like Our Station", Toast.LENGTH_LONG)
.show();
// Like increament
/*
* HttpClient httpclient = new DefaultHttpClient(); HttpPost
* httppost = new HttpPost(
* "http://www.vaibhavtech.com/work/android/radio_like.php");
*
* try { // Add your data List<NameValuePair> nameValuePairs =
* new ArrayList<NameValuePair>( 1); nameValuePairs.add(new
* BasicNameValuePair("id", Tab_Listner.id));
*
*
*
* httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
*
* // Execute HTTP Post Request
*
* ResponseHandler<String> responseHandler = new
* BasicResponseHandler(); String response =
* httpclient.execute(httppost, responseHandler);
*
* // This is the response from a php application String
* reverseString = response; Log.i("response", reverseString);
*
* } catch (ClientProtocolException e) { Log.i("CPE response ",
* e.toString()); // TODO Auto-generated catch block } catch
* (IOException e) { Log.i("IOException response ",
* e.toString()); // TODO Auto-generated catch block }
*/
}
});
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
playButton = (ImageView) findViewById(R.id.imageView1);
playButton.setEnabled(false);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("Click sadg ", "success");
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
if (audioStreamer.getMediaPlayer().isPlaying()) {
Log.i("play ", "success");
audioStreamer.getMediaPlayer().pause();
playButton.setImageResource(R.drawable.play_radio_play);
} else {
Log.i("pause", "success");
audioStreamer.getMediaPlayer().start();
audioStreamer.startPlayProgressUpdater();
playButton.setImageResource(R.drawable.play_radio_pause);
}
isPlaying = !isPlaying;
}
});
// rating radio sation
ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
rankBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialog = new Dialog(Play_Radio.this,
R.style.FullHeightDialog);
rankDialog.setContentView(R.layout.rating_bar);
rankDialog.setCancelable(true);
ratingBar = (RatingBar) rankDialog
.findViewById(R.id.dialog_ratingbar);
float userRankValue = 0;
// ratingBar.setRating(userRankValue);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// TODO Auto-generated method stub
cus_rating = rating;
}
});
Button updateButton = (Button) rankDialog
.findViewById(R.id.rank_dialog_button);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Play_Radio.this,
"Thanks For Rating Our Stations",
Toast.LENGTH_LONG).show();
/*
* HttpClient httpclient = new DefaultHttpClient();
* HttpPost httppost = new HttpPost(
* "http://www.vaibhavtech.com/work/android/radio_rat.php"
* );
*
* try { // Add your data List<NameValuePair>
* nameValuePairs = new ArrayList<NameValuePair>( 3);
* nameValuePairs.add(new BasicNameValuePair("id",
* Tab_Listner.id)); nameValuePairs.add(new
* BasicNameValuePair("rate", "" + cus_rating));
* nameValuePairs.add(new BasicNameValuePair("type", ""
* + 2)); httppost.setEntity(new UrlEncodedFormEntity(
* nameValuePairs));
*
* // Execute HTTP Post Request
*
* ResponseHandler<String> responseHandler = new
* BasicResponseHandler(); String response =
* httpclient.execute(httppost, responseHandler);
*
* // This is the response from a php application String
* reverseString = response; Log.i("response",
* reverseString);
*
* } catch (ClientProtocolException e) {
* Log.i("CPE response ", e.toString()); // TODO
* Auto-generated catch block } catch (IOException e) {
* Log.i("IOException response ", e.toString()); // TODO
* Auto-generated catch block }
*/
rankDialog.dismiss();
}
});
// now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
String urlstring2 = Tab_Listner.radio_url;
Toast.makeText(Play_Radio.this,
"Please Wait ...Radio Is Gonna To Play...", Toast.LENGTH_LONG)
.show();
startStreamingAudio(urlstring2);
tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}
private void startStreamingAudio(String urlstring) {
try {
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (audioStreamer != null) {
audioStreamer.interrupt();
}
audioStreamer = new StreamingMediaPlayer(this, textStreamed,
playButton, progressBar);
audioStreamer.startStreaming(urlstring, 5208, 216);
// streamButton.setEnabled(false);
// playButton.setEnabled(true);
} catch (Exception e) {
Log.e(getClass().getName(), "Error starting to stream audio.", e);
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
}
how to add progress bar spinner in this code. spinner work like youtube after then buffering start its stop. plz help me.i am already add progress bar but they can not working now. plz check tuneup on google play.enter link description here
In your XML add a progress bar element, then hide/show this element when you want to see the progress bar.
<!-- Show spinner by default and set to 'gone' when load is complete -->
<ProgressBar
android:id="#+id/myProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/Widget.ProgressBar.Small"
android:layout_marginLeft="5dp"
android:indeterminate="true" />
Hiding the progress bar in your code:
ProgressBar pBar = (ProgressBar)vi.findViewById(R.id.myProgressBar);
pBar.setVisibility(View.GONE);
.. show again with:
pBar.setVisibility(View.VISIBLE);
You can make those calls around the same time you show your toast messages that the load has started.
i have gone through this link https://code.google.com/p/android-lockpattern/ to apply pattern functionality in my application. But i am facing some issues, I have created continue button to move to next screen for confirming the pattern but its not working at all. I want that when user starts to draw the pattern on the first screen continue button should start working but its not working so. Please tell me the solution.I am attaching my MainActivity.java code.
Thanks in advance
package com.example.lock_pattern;
import com.example.lock_pattern.prefs.DisplayPrefs;
public class MainActivity extends Activity {
private static final String CLASSNAME = MainActivity.class.getName();
public static final String ACTION_CREATE_PATTERN = CLASSNAME
+ ".create_pattern";
public static final String ACTION_COMPARE_PATTERN = CLASSNAME
+ ".compare_pattern";
public static final String ACTION_VERIFY_CAPTCHA = CLASSNAME
+ ".verify_captcha";
* If you use {#link #ACTION_COMPARE_PATTERN} and the user fails to "login"
public static final int RESULT_FAILED = RESULT_FIRST_USER + 1;
* If you use {#link #ACTION_COMPARE_PATTERN} and the user forgot his/ her
public static final int RESULT_FORGOT_PATTERN = RESULT_FIRST_USER + 2;
* If you use {#link #ACTION_COMPARE_PATTERN}, and the user fails to "login"
public static final String EXTRA_RETRY_COUNT = CLASSNAME + ".retry_count";
* Sets value of this key to a theme in {#code R.style.Alp_Theme_*}. Default
public static final String EXTRA_THEME = CLASSNAME + ".theme";
* Key to hold the pattern. It must be a {#code char[]} array.
public static final String EXTRA_PATTERN = CLASSNAME + ".pattern";
* You can provide an {#link ResultReceiver} with this key. The activity
public static final String EXTRA_RESULT_RECEIVER = CLASSNAME
+ ".result_receiver";
* Put a {#link PendingIntent} into this key. It will be sent before
public static final String EXTRA_PENDING_INTENT_OK = CLASSNAME
+ ".pending_intent_ok";
* Put a {#link PendingIntent} into this key. It will be sent before
public static final String EXTRA_PENDING_INTENT_CANCELLED = CLASSNAME
+ ".pending_intent_cancelled";
* You put a {#link Intent} of <i>{#link Activity}</i> into this extra. The
public static final String EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN = CLASSNAME
+ ".intent_activity_forgot_pattern";
* Helper enum for button OK commands. (Because we use only one "OK" button
private static enum ButtonOkCommand {
CONTINUE, FORGOT_PATTERN, DONE
}// ButtonOkCommand
* Delay time to reload the lock pattern view after a wrong pattern.
private static final long DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW = DateUtils.SECOND_IN_MILLIS;
/*
* FIELDS
*/
private int mMaxRetry;
private boolean mAutoSave;
private IEncrypter mEncrypter;
private int mMinWiredDots;
private ButtonOkCommand mBtnOkCmd;
private Intent mIntentResult;
private int mRetryCount = 0;
/*
* CONTROLS
*/
private TextView mTextInfo;
private LockPatternView mLockPatternView;
private View mFooter;
private Button mBtnCancel;
private Button mBtnConfirm;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "ClassName = " + CLASSNAME);
/*
* EXTRA_THEME
*/
if (getIntent().hasExtra(EXTRA_THEME))
setTheme(getIntent().getIntExtra(EXTRA_THEME,
R.style.Alp_Theme_Dark));
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "oncreate", 7000).show();
mMinWiredDots = DisplayPrefs.getMinWiredDots(this);
mMaxRetry = DisplayPrefs.getMaxRetry(this);
mAutoSave = SecurityPrefs.isAutoSavePattern(this);
/*
* Encrypter.
*/
char[] encrypterClass = SecurityPrefs.getEncrypterClass(this);
if (encrypterClass != null) {
try {
mEncrypter = (IEncrypter) Class.forName(
new String(encrypterClass), false, getClassLoader())
.newInstance();
} catch (Throwable t) {
throw new InvalidEncrypterException();
}
}
mIntentResult = new Intent();
setResult(RESULT_CANCELED, mIntentResult);
initContentView();
}// onCreate()
#Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(CLASSNAME, "onConfigurationChanged()");
super.onConfigurationChanged(newConfig);
initContentView();
}// onConfigurationChanged()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Toast.makeText(getApplicationContext(), "Inside onKeyDown", Toast.LENGTH_LONG).show();
if (keyCode == KeyEvent.KEYCODE_BACK
&& ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* Use this hook instead of onBackPressed(), because onBackPressed()
* is not available in API 4.
*/
finishWithNegativeResult(RESULT_CANCELED);
return true;
}
return super.onKeyDown(keyCode, event);
}// onKeyDown()
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "onDestroy()");
}// onDestroy()
/**
* Initializes UI...
*/
private void initContentView() {
/*
* Save all controls' state to restore later.
*/
CharSequence infoText = mTextInfo != null ? mTextInfo.getText() : null;
Boolean btnOkEnabled = mBtnConfirm != null ? mBtnConfirm.isEnabled()
: null;
LockPatternView.DisplayMode lastDisplayMode = mLockPatternView != null ? mLockPatternView
.getDisplayMode() : null;
List<Cell> lastPattern = mLockPatternView != null ? mLockPatternView
.getPattern() : null;
setContentView(R.layout.activity_main);
UI.adjustDialogSizeForLargeScreen(getWindow());
mTextInfo = (TextView) findViewById(R.id.alp_textview_info);
mLockPatternView = (LockPatternView) findViewById(R.id.alp_view_lock_pattern);
mFooter = findViewById(R.id.alp_viewgroup_footer);
mBtnCancel = (Button) findViewById(R.id.alp_button_cancel);
mBtnConfirm = (Button) findViewById(R.id.alp_button_confirm);
/*
* LOCK PATTERN VIEW
*/
if (getResources().getBoolean(R.bool.alp_is_large_screen)) {
int size = getResources().getDimensionPixelSize(
R.dimen.alp_lockpatternview_size);
LayoutParams lp = mLockPatternView.getLayoutParams();
lp.width = size;
lp.height = size;
mLockPatternView.setLayoutParams(lp);
}
/*
* Haptic feedback.
*/
boolean hapticFeedbackEnabled = false;
try {
hapticFeedbackEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0;
} catch (Throwable t) {
/*
* Ignore it.
*/
}
mLockPatternView.setTactileFeedbackEnabled(hapticFeedbackEnabled);
mLockPatternView.setInStealthMode(DisplayPrefs.isStealthMode(this)
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()));
mLockPatternView.setOnPatternListener(mLockPatternViewListener);
if (lastPattern != null && lastDisplayMode != null
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()))
mLockPatternView.setPattern(lastDisplayMode, lastPattern);
/*
* COMMAND BUTTONS
*/
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
Toast.makeText(getApplicationContext(), "initContentView", 7000).show();
mBtnCancel.setOnClickListener(mBtnCancelOnClickListener);
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnCancel.setVisibility(View.VISIBLE);
mBtnConfirm.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
if (infoText != null)
mTextInfo.setText(infoText);
else
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
/*
* BUTTON OK
*/
if (mBtnOkCmd == null)
mBtnOkCmd = ButtonOkCommand.CONTINUE;
switch (mBtnOkCmd) {
case CONTINUE:
mBtnConfirm.setText(R.string.alp_cmd_continue);
break;
case DONE:
mBtnConfirm.setText(R.string.alp_cmd_confirm);
break;
default:
/*
* Do nothing.
*/
break;
}
if (btnOkEnabled != null)
mBtnConfirm.setEnabled(btnOkEnabled);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
if (TextUtils.isEmpty(infoText))
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
else
mTextInfo.setText(infoText);
if (getIntent().hasExtra(EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN)) {
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnConfirm.setText(R.string.alp_cmd_forgot_pattern);
mBtnConfirm.setEnabled(true);
mFooter.setVisibility(View.VISIBLE);
}
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
final ArrayList<Cell> pattern;
if (getIntent().hasExtra(EXTRA_PATTERN))
pattern = getIntent()
.getParcelableArrayListExtra(EXTRA_PATTERN);
else
getIntent().putParcelableArrayListExtra(
EXTRA_PATTERN,
pattern = LockPatternUtils
.genCaptchaPattern(DisplayPrefs
.getCaptchaWiredDots(this)));
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// initContentView()
* Encodes {#code pattern} to a string.
private char[] encodePattern(List<Cell> pattern) {
* Compares {#code pattern} to the given pattern (
private void doComparePattern(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside doComparePattern", Toast.LENGTH_LONG).show();
if (pattern == null)
return;
boolean okey = false;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
char[] currentPattern = getIntent()
.getCharArrayExtra(EXTRA_PATTERN);
if (currentPattern == null)
currentPattern = SecurityPrefs.getPattern(this);
okey = Arrays.equals(encodePattern(pattern), currentPattern);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
final List<Cell> captchaPattern = getIntent()
.getParcelableArrayListExtra(EXTRA_PATTERN);
okey = captchaPattern.size() == pattern.size();
if (okey) {
for (int i = 0; i < captchaPattern.size(); i++) {
if (!captchaPattern.get(i).equals(pattern.get(i))) {
okey = false;
break;
}
}// for
}
}// ACTION_VERIFY_CAPTCHA
if (okey)
finishWithResultOk(null);
else {
mRetryCount++;
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
if (mRetryCount >= mMaxRetry)
finishWithNegativeResult(RESULT_FAILED);
else {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(R.string.alp_msg_try_again);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
}
}// doComparePattern()
/**
* Checks and creates the pattern.
*
* #param pattern
* the current pattern of lock pattern view.
*/
private void doCheckAndCreatePattern(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside doCheckAndCreatePattern", Toast.LENGTH_LONG).show();
if (pattern.size() < mMinWiredDots) {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(getResources().getQuantityString(
R.plurals.alp_pmsg_connect_x_dots, mMinWiredDots,
mMinWiredDots));
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
return;
}
if (getIntent().hasExtra(EXTRA_PATTERN)) {
if (Arrays.equals(getIntent().getCharArrayExtra(EXTRA_PATTERN),
encodePattern(pattern))) {
mTextInfo.setText(R.string.alp_msg_your_new_unlock_pattern);
mBtnConfirm.setEnabled(true);
} else {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setEnabled(false);
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
} else {
getIntent().putExtra(EXTRA_PATTERN, encodePattern(pattern));
mTextInfo.setText(R.string.alp_msg_pattern_recorded);
mBtnConfirm.setEnabled(true);
}
}// doCheckAndCreatePattern()
* Finishes activity with {#link Activity#RESULT_OK}.
private void finishWithResultOk(char[] pattern) {
Toast.makeText(getApplicationContext(), "Inside finishWithResultOk", Toast.LENGTH_LONG).show();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be zero.
*/
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
setResult(RESULT_OK, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle bundle = new Bundle();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
bundle.putCharArray(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be
* zero.
*/
bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
receiver.send(RESULT_OK, bundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_OK);
if (pi != null) {
try {
pi.send(this, RESULT_OK, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithResultOk()
/**
* Finishes the activity with negative result (
* {#link Activity#RESULT_CANCELED}, {#link #RESULT_FAILED} or
* {#link #RESULT_FORGOT_PATTERN}).
*/
private void finishWithNegativeResult(int resultCode) {
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
setResult(resultCode, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle resultBundle = null;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
resultBundle = new Bundle();
resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount);
}
receiver.send(resultCode, resultBundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_CANCELLED);
if (pi != null) {
try {
pi.send(this, resultCode, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithNegativeResult()
/*
* LISTENERS
*/
private final LockPatternView.OnPatternListener mLockPatternViewListener = new LockPatternView.OnPatternListener() {
#Override
public void onPatternStart() {
Toast.makeText(getApplicationContext(), "Inside onPatternStart", Toast.LENGTH_LONG).show();
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
mLockPatternView.setDisplayMode(DisplayMode.Correct);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
Toast.makeText(getApplicationContext(), "Inside action create pattern", Toast.LENGTH_LONG).show();
mTextInfo.setText(R.string.alp_msg_release_finger_when_done);
mBtnConfirm.setEnabled(true);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE)
getIntent().removeExtra(EXTRA_PATTERN);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_VERIFY_CAPTCHA
}// onPatternStart()
#Override
public void onPatternDetected(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside onPatternDetected", Toast.LENGTH_LONG).show();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
doCheckAndCreatePattern(pattern);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
doComparePattern(pattern);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
if (!DisplayMode.Animate.equals(mLockPatternView
.getDisplayMode()))
doComparePattern(pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternDetected()
#Override
public void onPatternCleared() {
Toast.makeText(getApplicationContext(), "Inside onPatternCleared", Toast.LENGTH_LONG).show();
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mBtnConfirm.setEnabled(true);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
getIntent().removeExtra(EXTRA_PATTERN);
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
} else
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
List<Cell> pattern = getIntent().getParcelableArrayListExtra(
EXTRA_PATTERN);
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternCleared()
#Override
public void onPatternCellAdded(List<Cell> pattern) {
// TODO Auto-generated method stub
}// onPatternCellAdded()
};// mLockPatternViewListener
private final View.OnClickListener mBtnCancelOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
finishWithNegativeResult(RESULT_CANCELED);
}// onClick()
};// mBtnCancelOnClickListener
private final View.OnClickListener mBtnConfirmOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
mBtnOkCmd = ButtonOkCommand.DONE;
mLockPatternView.clearPattern();
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setText(R.string.alp_cmd_confirm);
mBtnConfirm.setEnabled(false);
} else {
final char[] pattern = getIntent().getCharArrayExtra(
EXTRA_PATTERN);
if (mAutoSave)
SecurityPrefs.setPattern(MainActivity.this,
pattern);
finishWithResultOk(pattern);
}
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* We don't need to verify the extra. First, this button is only
* visible if there is this extra in the intent. Second, it is
* the responsibility of the caller to make sure the extra is an
* Intent of Activity.
*/
startActivity((Intent) getIntent().getParcelableExtra(
EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN));
finishWithNegativeResult(RESULT_FORGOT_PATTERN);
}// ACTION_COMPARE_PATTERN
}// onClick()
};// mBtnConfirmOnClickListener
/**
* This reloads the {#link #mLockPatternView} after a wrong pattern.
*/
private final Runnable mLockPatternViewReloader = new Runnable() {
#Override
public void run() {
mLockPatternView.clearPattern();
mLockPatternViewListener.onPatternCleared();
}// run()
};// mLockPatternViewReloader
}
Your bug is in your initialization in initContentView(). You are setting btnOkEnabled before you've loaded the button into mBtnConfirm.
Move your findViewById() calls to the top of that method and you should be all set.
java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.
at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:2772)
at android.webkit.WebViewCore$EventHub.access$13800(WebViewCore.java:1434)
at android.webkit.WebViewCore.removeMessages(WebViewCore.java:2884)
at android.webkit.WebView.sendOurVisibleRect(WebView.java:4140)
at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:1022)
at android.webkit.ZoomManager.access$2100(ZoomManager.java:57)
at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:1596)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
when i set "webSettings.setPluginState(PluginState.ON)" happen this questions,
this is my code :
package com.etongwl.test.androidtestdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
public class WebViewActivity extends Activity {
/**
* 浏览器对象
*/
private WebView webView = null;
/**
* 进度条
*/
private ProgressBar progressBar = null;
/**
* 加载的URL
*/
private String url = null;
/**
* handler
*/
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
progressBar.setProgress(msg.arg1);
} else if (msg.what == 2) {
progressBar.setVisibility(ProgressBar.VISIBLE);
} else if (msg.what == 3) {
progressBar.setVisibility(ProgressBar.GONE);
}
};
};
#SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
/**
* 获得屏幕的宽高
*/
DisplayMetrics dm = new DisplayMetrics();
// 取得窗口属性
getWindowManager().getDefaultDisplay().getMetrics(dm);
// 窗口的宽度
int screenWidth = dm.widthPixels;
// 窗口高度
int screenHeight = dm.heightPixels;
LinearLayout layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(screenWidth, screenHeight);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(params);
layout.setBackgroundColor(Color.WHITE);
setContentView(layout);
// 获得状态栏高度
int statusBarHeight = getStatusHeight(this);
Intent intent = getIntent();
url = intent.getStringExtra("URL");
// 标题
RelativeLayout view = (RelativeLayout) getLayoutInflater().inflate(
R.layout.webviewheader, null);
Button back = (Button) view.findViewById(R.id.btn_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
view.setLayoutParams(new LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
int w = RelativeLayout.MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
int h = RelativeLayout.MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
view.measure(w, h);
int x = view.getMeasuredHeight();
layout.addView(view);
// 进度条
progressBar = new ProgressBar(this, null,
android.R.attr.progressBarStyleHorizontal);
LinearLayout.LayoutParams param = new android.widget.LinearLayout.LayoutParams(
screenWidth - 2, 3);
param.setMargins(1, 2, 1, 2);
progressBar.setLayoutParams(param);
progressBar.setMax(100);
layout.addView(progressBar);
// webView浏览器
webView = new WebView(this);
LinearLayout.LayoutParams paramW = new android.widget.LinearLayout.LayoutParams(
screenWidth, screenHeight - x - 7 - statusBarHeight);
webView.setLayoutParams(paramW);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
// webSettings.setDisplayZoomControls(true);
// webSettings.setUseWideViewPort(true);
// webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
// webSettings.setAllowFileAccessFromFileURLs(true);
// webSettings.setAllowUniversalAccessFromFileURLs(true);
// webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
// webSettings.setEnableSmoothTransition(true);
// webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setPluginsEnabled(true);
webSettings.setPluginState(PluginState.ON);
webView.setBackgroundColor(Color.WHITE);
layout.addView(webView);
webView.setWebChromeClient(new WebChromeClient() {
/*
* (non-Javadoc)
*
* #see
* android.webkit.WebChromeClient#onProgressChanged(android.webkit
* .WebView, int)
*/
#Override
public void onProgressChanged(WebView view, int newProgress) {
// super.onProgressChanged(view, newProgress);
Message msg = handler.obtainMessage();
msg.what = 1;
msg.arg1 = newProgress;
msg.sendToTarget();
}
});
webView.setWebViewClient(new WebViewClient() {
/*
* (non-Javadoc)
*
* #see
* android.webkit.WebViewClient#shouldOverrideUrlLoading(android
* .webkit.WebView, java.lang.String)
*/
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
/*
* (non-Javadoc)
*
* #see
* android.webkit.WebViewClient#onPageStarted(android.webkit.WebView
* , java.lang.String, android.graphics.Bitmap)
*/
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// super.onPageStarted(view, url, favicon);
Message msg = handler.obtainMessage();
msg.what = 2;
msg.sendToTarget();
}
/*
* (non-Javadoc)
*
* #see
* android.webkit.WebViewClient#onPageFinished(android.webkit.WebView
* , java.lang.String)
*/
#Override
public void onPageFinished(WebView view, String url) {
// super.onPageFinished(view, url);
Message msg = handler.obtainMessage();
msg.what = 3;
msg.sendToTarget();
}
});
if (url != null) {
webView.loadUrl(url);
} else {
webView.loadUrl("一个swf文件路径");
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
// android.os.Process.killProcess(android.os.Process.myPid());
}
}
/**
*
* #Des: 获得状态栏高度
* #param activity
* #return
*/
public int getStatusHeight(Activity activity) {
int statusHeight = 0;
Rect localRect = new Rect();
activity.getWindow().getDecorView()
.getWindowVisibleDisplayFrame(localRect);
statusHeight = localRect.top;
if (0 == statusHeight) {
Class<?> localClass;
try {
localClass = Class.forName("com.android.internal.R$dimen");
Object localObject = localClass.newInstance();
int i5 = Integer.parseInt(localClass
.getField("status_bar_height").get(localObject)
.toString());
statusHeight = activity.getResources()
.getDimensionPixelSize(i5);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return statusHeight;
}
}
my project created by android 2.2 and run on android 4.0.4
Whether the installation is android2.2 or android4.0 flash player can run normally.
if i create project by android 4.0.4 and run android 4.0.4 normally
why?
please help me thanks
I need to change the content of progress dialog when sync activity is running it shows "synchronizing data"
when it has completed it goes for another background activity and still shows the same text what I want is to change the text when it goes to other background task?
protected void onPreExecute() {
mDialog = ProgressDialog.show(viewContext, "", "Synchronizing Data",
true);
};
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
if (type.contains("ferry")) {
return SynchronizeRepositoryFerry(false);
} else {
boolean value = SynchronizeRepositories(false, initialSync);
mDialog.setTitle("Loading Images");//FROM HERE I WANT TO CHANGE DIALOG
com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
IUserRepository repository = dbHelper.getUserRepository();
List<com.jumbybay.businessobjects.User> imageList;
try {
int id;
String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
imageList = repository.Retrieve();
for (int i = 0; i < imageList.size(); i++) {
user = imageList.get(i);
// url = user.getPicture();
id = user.getId();
fetchImage fetch = new fetchImage();
fetch.savesd(id, url);
}
} catch (SQLException e) {
// TODO Auto-generated catch block// url = user.getPicture();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
protected void onProgressUpdate(Integer... progress) {
mDialog.setTitle("lOADING IMAGES...");
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
this.syncComplete = result;
mDialog.dismiss();
Intent intent = new Intent();
intent.setClass(viewContext, classType);
viewContext.startActivity(intent);
}
have you tried using it like this
mDialog.setTitle("Loading Images");
mDialog.show();
private static String CONSUMER_KEY = "mrnCC41nxtwkdFAmToEhtg";
private static final String CONSUMER_SECRET = "kmmVuahEspGvdl14aCD1GSBZpeHbxvkpAez7aKaaQ";
EditText editPinCode;
LinearLayout lin;
public Logger slr;
LinearLayout container;
public LoginT(){
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
editPinCode = new EditText(this);
lin = (LinearLayout)findViewById(R.id.LinearLayout01);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
getTwitter(context);
}
/**
* Connects to twittter
* #param v
*/
public void getTwitter(Context ctx) { //updated code
handleEvent.post(new Runnable() {
// handleEvent.postAtFrontOfQueue(new Runnable() {
public void run() {
if (oHelper.hasAccessToken())
{
Log.e("run if","run");
oHelper.configureOAuth(twitterConnection);
try
{
i=i+1;
Log.e("run try","run");
twitterConnection.updateStatus(Calendar.MINUTE+i+"Hi this is Arun......");
//twitterConnection.se
Log.e("finish","start");
finish();
Log.e("finish","end");
}
catch (TwitterException e)
{
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
}
else
{
Log.e("run else","run");
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
requestToken = twitterConnection.getOAuthRequestToken("");
Log.e("REQUEST_TOKEN",requestToken+"");
webViewDialog(requestToken.getAuthorizationURL(), 0);
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
}});
}
/**
* Shows Dialog for authentications
*
* #param authorizationURL
* #param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
Log.e("webViewDialog","webViewDialog");
container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
// webView.dispatchWindowFocusChanged(true);
webView.setWebViewClient(new MyWebViewClient(this,LoginT.this));
webView.loadUrl(authorizationURL);
container.addView(webView);
lin.addView(container);
// Builder webDialog = new AlertDialog.Builder(this);
// webDialog.setView(container).setTitle("Twitter Client").setCancelable(true)
// .show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
try {
// accessToken = twitterConnection.getOAuthAccessToken(requestToken,ss);
try{
accessToken = twitterConnection.getOAuthAccessToken(requestToken);
}
catch(Exception e1){
Log.w("Excep e1",e1+"");
}
oHelper.storeAccessToken(accessToken);
Log.w("ohelper",oHelper.toString());
twitterConnection.updateStatus("Tweeted Successfully"+new Date().toString());
Log.e(" ","2 "+accessToken);
Log.e(" ","3");
webView.destroy();
webView.removeAllViews();
container.removeAllViews();
this.finish();
// Log.i("Access Token:", accessToken.getToken());
// Log.i("Access Secret:", accessToken.getTokenSecret());
} catch (TwitterException te) {
oHelper.storeAccessToken(accessToken);
try {
twitterConnection.updateStatus("HI.... ");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
// case DIALOG_LOADING:
// {
// // dialog = new ProgressDialog(this);
// dialog.setMessage("Please wait while loading...");
// dialog.setIndeterminate(true);
// dialog.setCancelable(true);
// return dialog;
// }
}
return null;
}
//
// #Override
public void dismiss() {
Log.w("dismiss","dismiss");
try{
// webView.destroy();
// webView.removeAllViews();
// container.removeAllViews();
// this.finish();
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
//
#Override
public boolean onSearchRequested() {
Log.e("Search","Search");
return super.onSearchRequested();
}
I use the above Code for making connection for twitter but it only works for one time if I want another time for connection then it never provide me second time connection.
Thankx
Could this be an Activity lifecycle issue? Your call to getTwitter() occurs in onCreate, which only gets called when the Activity is created. If a user navigates away then comes back to your app, it may still be running, so onCreate would not get called again. Have a look at the Activity lifecycle, and add some debug code to each of the lifecycle methods (onResume, onPause etc) to get an idea of when they are called.