Webview shows white blank page in Ice Cream Sandwitch - java

In my webview I have loaded a URL which have an embeded video player of a tv channel live stream. It is working correctly in all the OS version of Android except ICS(4). First time It plays the video well, but when I go back and come again in that page containing the video then the video doesnt loads and shows a blank white page. If I force stop the app from the application setting and start the app again then It runs well then appears white screen again as usual, I have implemented a lot of tactics and this is the latest , I am totally stuck here:
public class Livetvwebview extends Activity {
RelativeLayout a;
WebView webtv;
String url;
VideoView video;
WChromeClient chromeClient;
WebViewClient wvClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.livewebview);
Toast.makeText(getApplicationContext(),
"Channel is loading..This may take upto a minute",
Toast.LENGTH_LONG).show();
url = getIntent().getStringExtra("tvchannel");
Log.i("TVURL", url);
webtv = (WebView) findViewById(R.id.webViewlive);
webtv.clearCache(true);
webtv.loadUrl(url);
webtv.getSettings().setLoadWithOverviewMode(true);
webtv.getSettings().setUseWideViewPort(true);
webtv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webtv.setWebChromeClient(new WChromeClient());
webtv.setWebViewClient(new myWebClient());
webtv.getSettings().setJavaScriptEnabled(true);
webtv.getSettings().setPluginState(PluginState.ON);
webtv.getSettings().setDomStorageEnabled(true);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
// TODO Auto-generated method stub
WebSettings webSettings = webtv.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webtv.onPause();
this.finish();
super.onPause();
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
webtv.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
// android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache",
Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
class WChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
Log.i("Method", "Onrogresschanged");
Livetvwebview.this.setTitle("Loading...");
Livetvwebview.this.setProgress(progress * 100);
if (progress == 100)
Livetvwebview.this.setTitle("LiveTv");
}
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// TODO Auto-generated method stub
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
webtv.setVisibility(View.GONE);
video = (VideoView) frame.getFocusedChild();
FrameLayout.LayoutParams par = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
par.gravity = Gravity.CENTER_HORIZONTAL;
video.setLayoutParams(par);
frame.removeView(video);
a.addView(video);
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(Livetvwebview.this,
"Video completed", Toast.LENGTH_LONG)
.show();
}
});
video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what,
int extra) {
Toast.makeText(Livetvwebview.this,
"Encountered some error", Toast.LENGTH_LONG)
.show();
return true;
}
});
video.start();
}
}
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Can anyone help me please?

After researching for a long long time I myself figured out that when I write in the onPause()
webtv.destroy();
instead of
webtv.onPause();
solves the problem :)

Related

How to handle on back pressed method

I have source for play station 1 games.
I want when user click to start button and go to play activity.
user can click on back pressed or show a button to go previos activity.
my onbackpressed method not dont work.and there is no view to add button.
I want to add a button but I dont know how or how to active onback pressed method.
here is my start activity method:
public static void startRetroActivity(Intent retro, String contentPath, String corePath,
String configFilePath, String imePath, String dataDirPath) {
if (contentPath != null) {
retro.putExtra("ROM", "/storage/emulated/0/" + ctx.getPackageName() + "/images/data.bin");
}
retro.putExtra("LIBRETRO", corePath);
retro.putExtra("CONFIGFILE", configFilePath);
retro.putExtra("IME", imePath);
retro.putExtra("DATADIR", dataDirPath);
}
and here I use this method:
Intent retro;
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) {
// Toast.makeText(getActivity(), "111", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityFuture.class);
} else {
// Toast.makeText(getActivity(), "222", Toast.LENGTH_LONG).show();
retro = new Intent(getActivity(), RetroActivityPast.class);
}
UserPreferences.updateConfigFile(getActivity());
MainMenuFragment.startRetroActivity(
retro,
ctx.getApplicationInfo().dataDir + (new StringBuilder(ikol)).reverse().toString(),
ctx.getApplicationInfo().dataDir + "/cores/pcsx_rearmed_libretro_neon_android.so",
UserPreferences.getDefaultConfigPath(getActivity()),
Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD),
getActivity().getApplicationInfo().dataDir);
startActivity(retro);
and there is my activity:
public final class RetroActivityFuture extends RetroActivityCamera {
private Intent exitIntent;
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
//stopService(exitIntent);
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//exitIntent = new Intent(this , AdService.class);
super.onCreate(savedInstanceState);
}
#Override
public void onStop() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onStop();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//stopService(exitIntent);
//startService(exitIntent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//stopService(exitIntent);
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
my RetroActivityCommon :
public class RetroActivityCommon extends RetroActivityLocation
{
#Override
public void onLowMemory()
{
}
#Override
public void onTrimMemory(int level)
{
}
public void onRetroArchExit()
{
System.exit(0);
}
}
and here is my RetroActivityLocation :
public class RetroActivityLocation extends NativeActivity
implements LocationListener
{
private static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
private Location mCurrentLocation;
LocationRequest mLocationRequest = null;
boolean mUpdatesRequested = false;
boolean locationChanged = false;
boolean location_service_running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void onLocationSetInterval(int update_interval_in_ms, int distance_interval)
{
if (mLocationRequest == null)
return;
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (update_interval_in_ms == 0)
mLocationRequest.setInterval(5 * 1000);
else
mLocationRequest.setInterval(update_interval_in_ms);
mLocationRequest.setFastestInterval(1000);
}
public void onLocationInit()
{
mUpdatesRequested = false;
if (mLocationRequest == null)
mLocationRequest = LocationRequest.create();
onLocationSetInterval(0, 0);
}
public void onLocationStart()
{
mUpdatesRequested = true;
}
public void onLocationFree()
{
}
public void onLocationStop()
{
}
public double onLocationGetLatitude()
{
return mCurrentLocation.getLatitude();
}
public double onLocationGetLongitude()
{
return mCurrentLocation.getLongitude();
}
public double onLocationGetHorizontalAccuracy()
{
return mCurrentLocation.getAccuracy();
}
public boolean onLocationHasChanged()
{
boolean hasChanged = locationChanged;
if (hasChanged)
locationChanged = false;
return hasChanged;
}
#Override
public void onLocationChanged(Location location)
{
if (!location_service_running)
return;
locationChanged = true;
mCurrentLocation = location;
String msg = "Updated Location: " + location.getLatitude() + ", " + location.getLongitude();
Log.i("RetroArch GPS", msg);
}
#Override
public void onStop()
{
onLocationStop();
super.onStop();
}
}
look in acivity I have nothing.and RetroActivityCamera extend native activity.
any suggestion?
Try calling finish() in onBackPressed method.

Handling OnPause and OnResume inside fragments android

I am trying to communicate with USB using InputOutput stream, I use constructor and make the communication part in a common class and I do use it inside a fragment, if i use it inside an activity it works properly if i use inside a fragment, the application hangs to overcome the problem i terminated the connection while OnPause but while resume connection not retains only on fragment same logic works on activity, I use some animations inside like Video is that be a reason?
#SuppressLint("ValidFragment")
public class Run_Screen extends Fragment implements OnClickListener {
Usb_Communciation usbCom;
RelativeLayout R_RelativeLayout, Run_Screen_Layout, Screen_Lock_Layout;
static SharedPreferences sharedpreferences;
Animation wipe;
static int machine;
MyLog myLog = new MyLog();
View root = null;
static Activity thisActivity = null;
#Override
public void onAttach(Activity activity) {
act = activity;
super.onAttach(activity);
thisActivity = Run_Screen.this.getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Vars.Screen_Size == 400) {
root = inflater.inflate(R.layout.run_screen_400, container, false);
} else if (Vars.Screen_Size == 600) {
root = inflater.inflate(R.layout.run_screen_600, container, false);
} else if (Vars.Screen_Size == 800) {
root = inflater.inflate(R.layout.run_screen_800, container, false);
} else {
root = inflater.inflate(R.layout.run_screen, container, false);
}
sharedpreferences = this.getActivity().getSharedPreferences(Vars.MyPre, Context.MODE_PRIVATE);
GlobalClass.Current_Screen = "Run_Screen";
cmg = new Comment_Generate(act);
R_Wiper = (ImageButton) root.findViewById(R.id.R_Wiper);
wipe = AnimationUtils.loadAnimation(act, R.anim.wipe);
wipe.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.INVISIBLE);
R_Wiper.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
Wiper_anim.setVisibility(View.VISIBLE);
}
});
R_Pause_Play.setOnClickListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
usbCom = new Usb_Communciation(Run_Screen.this.getActivity(), getActivity().getIntent());
}
#Override
public void onPause() {
super.onPause();
Usb_Communciation.AppDisconnect(Run_Screen.this.getActivity());
}
public void CheckFunc(){
if(Vars.ChangeMAchine==1){
R_Progress.setVisibility(View.VISIBLE);
R_Separator.setVisibility(View.VISIBLE);
R_Run.setVisibility(View.INVISIBLE);
R_Pause.setVisibility(View.VISIBLE);
R_Stop.setVisibility(View.VISIBLE);
R_Pause_Play.setVisibility(View.INVISIBLE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.R_Pause_Play:
DisableAll();
Reset_Machine_State(-2);
Vars.ChangeMAchine=1;
CheckFunc();
R_Progress.setVisibility(View.VISIBLE);
Send_Comment(Vars.C_Start_Machine, 0, 0);
myLog.Cmd("Write", Vars.C_Start_Machine, "0", "0",
"Start The Machine");
break;
}
}
private void Send_Comment(String Comment_No, int Address, int Data) {
Sending_Comment = cmg.Generate_Comment_for(Comment_No, Address, Data);
usbCom.Send_message(Sending_Comment);
}
public void SetUserLevelControls() {
Vars.CurrentUserLevel = sharedpreferences.getInt(Vars.UserLevel, 5);
if (Permission.Launcher_Operator_Screen_Defect_Height <= Vars.CurrentUserLevel) {
Screen_Lock_Layout.setVisibility(View.GONE);
} else {
Screen_Lock_Layout.setVisibility(View.VISIBLE);
}
if (Permission.Launcher_Operator_Screen_General <= Vars.CurrentUserLevel) {
R_Run.setOnClickListener(this);
R_Pause.setOnClickListener(this);
R_Stop.setOnClickListener(this);
R_Pause_Play.setOnClickListener(this);
Run_Lock.setVisibility(View.GONE);
} else {
R_Run.setOnClickListener(null);
R_Pause.setOnClickListener(null);
R_Stop.setOnClickListener(null);
R_Pause_Play.setOnClickListener(null);
Run_Lock.setVisibility(View.VISIBLE);
}
}
}
constructor class
public Usb_Communciation(Context mContext, Intent intent) {
try {
PackageManager manager = mContext.getPackageManager();
PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
Log.d(TAG, "Info:" + info.packageName + "\n" + info.versionCode + "\n" + info.versionName);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
accessoryManager.enable(mContext, intent);
}
AppDisconnect
public static void AppDisconnect(Context context) {
switch(firmwareProtocol) {
case 2:
byte[] commandPacket = new byte[2];
commandPacket[0] = (byte) APP_DISCONNECT;
commandPacket[1] = 0;
accessoryManager.write(commandPacket);
break;
}
try {
while(accessoryManager.isClosed() == false) {
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
accessoryManager.disable(context);
disconnectAccessory();
}

Android App StartApp Ads Error

I made a game and used an ads company on it (StartApp). I wanna use Interstitial Ads on it. I followed the step they show but can't achieve it. I'm getting error. Here is the LogCat:
http://i.stack.imgur.com/SaIXE.png
Here is the codes:
GameActivity.java
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException
{
StartAppAd.init(this, "10254544", "20454573");
}
MenuScene.java
private StartAppAd startAppAd = new StartAppAd(activity);
#Override
public void createScene() {
startAppAd.showAd();
startAppAd.loadAd();
}
Check the Manifest.xml file. Be sure you wrote the right package name in there.
Try This code and u should update manifest file also
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartAppSearch.showSearchBox(this);
StartAppAd.init(this, "107181003", "211487617");
StartAppSearch.init(this, "107181003", "211487617");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); //load next add
Intent intent=new Intent(getApplicationContext(),Second.class);
startActivity(intent);
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
boolean _active = true;
}
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
startAppAd.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
startAppAd.onResume();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private StartAppAd startAppAd = new StartAppAd(this);
#Override
public void onBackPressed() {
startAppAd.onBackPressed();
super.onBackPressed();
}
and update in manifest file also
You can not use the
startAppAd.showAd();
startAppAd.loadAd();
inside the Scene class (MenuScene). Instead you can try below method.
In GameActivity class you must be having KeyEvent method. put the code to show the startApp ads in there as below,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if(SceneManager.getInstance().getCurrentSceneType().toString() == "SCENE_MENU"){
try{
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
}catch(Exception e){
}
}
try{
SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
}catch(Exception e){
}
}
return false;
}
Regards,
Deepak

Application is repeatedly opened

I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.

Android - Intercept Link From Webview

So I need the user clicked link in webview, in this case it is a link containing a .pdf file. I have code that launches the PDF reader but it doesn't get the link so it just loads the PDF reader on click of a PDF file. How do I intercept this link and feed it to my PDF reader intent?
Code:
public class atcFaa extends Activity {
WebView webview;
private String url;
ProgressBar pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atccti);
pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
webview = (WebView) findViewById(R.id.ctiWebView);
webview.getSettings().setJavaScriptEnabled(true);
Button openPdfBtn = new Button(this);
webview.addJavascriptInterface(openPdfBtn, "openPdfBtn");
openPdfBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
openPdf();
}
});
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && pd.getVisibility() == ProgressBar.GONE) {
pd.setVisibility(ProgressBar.VISIBLE);
}
pd.setProgress(progress);
if (progress == 100) {
pd.setVisibility(ProgressBar.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.getSettings().setJavaScriptEnabled(true);
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL,
new String[] { url });
startActivity(i);
} else if (url.startsWith("geo:")) {
try {
} catch (Exception e) {
System.out.println(e);
}
} else if (url.endsWith("pdf")) {
try {
}
catch (ActivityNotFoundException e) {
Toast.makeText(atcFaa.this, "No PDF Viewer Installed",
Toast.LENGTH_LONG).show();
}
}
else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("http://www.faa.gov/air_traffic/publications/");
}
protected void openPdf() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.parse(url);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.atcAbout2:
Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG)
.show();
break;
case R.id.atcContact2:
emailme();
break;
}
return true;
}
private void emailme() {
// TODO Auto-generated method stub
String domsEmail = "MYEMAIL#EXAMPLE.com";
String message = "Insert Message Here";
String myemail[] = { domsEmail };
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, myemail);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"ATC Assistant");
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
startActivity(emailIntent);
}
/*
* #Override public void onBackPressed() { if (webview.canGoBack())
* webview.goBack(); else super.onBackPressed(); }
*/
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I don't know the structure of your html code, but I'll pretend you have a button. Here the code to have in your html:
<button onclick='openPdfBtn.performClick();'>Open pdf</button>
and then add a js interface to your webview:
Button openPdfBtn = new Button(this); //this is not gonna be visible
yourWebView.addJavascriptInterface(openPdfBtn, "openPdfBtn"); //here you bind the js with the native button
openPdfBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openPdf();
}
});

Categories