Android - Intercept Link From Webview - java

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();
}
});

Related

How to display a message in MainActivity if there is no Internet?

If there is no Internet, display a certain xml in full screen when the application starts, that there is no Internet, and if there is, perform MainActivity.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MaterialSearchBar.OnSearchActionListener, PopupMenu.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
#SuppressLint("StaticFieldLeak")
public static MaterialSearchBar searchBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private AdView mAdView;
private static List<String> listPermissionsNeeded;
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: setting things up");
StaticUtils.requestQueue = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Admob banner
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
mAdView.setVisibility(View.GONE);
}
});
//restoring recent searches list
StaticUtils.recentSearchesList = getArrayList(StaticUtils.KEY_LIST_PREFERENCCES);
if (StaticUtils.recentSearchesList==null){
StaticUtils.recentSearchesList = new ArrayList<>();
}
StaticUtils.savedImagesList = new ArrayList<>();
searchBar = findViewById(R.id.searchToolBar);
searchBar.setHint("Search Wallpapers");
searchBar.setOnSearchActionListener(this);
searchBar.hideSuggestionsList();
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//sets home fragment open by default
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
playLogoAudio(); //to play the logo audio
searchEvents(); //advanced search events
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: back button invoked.");
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void grantPermissionBottomSheet(){
View dialogView = getLayoutInflater().inflate(R.layout.layout_bottomsheet, null);
final BottomSheetDialog dialog = new BottomSheetDialog(this);
Button ok = dialogView.findViewById(R.id.bt_bottomsheet);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: bottomSheet button clicked.");
requestPermissions(MainActivity.this);
dialog.dismiss();
}
});
dialog.setContentView(dialogView);
dialog.show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d(TAG, "onNavigationItemSelected: navigation item pressed.");
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
} else if (id == R.id.nav_saved) {
NetworkUtils network = new NetworkUtils(this);
if(network.checkConnection(drawer)){ //if network connected
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,2);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"Saved");
startActivity(i);
}
}else if (id == R.id.nav_downloads) {
//downloaded images
if (permissionsGranted(this)) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID, 4); //4 for downloads section
i.putExtra(StaticUtils.KEY_SEARCH_DATA, "Downloads");
startActivity(i);
}else{
grantPermissionBottomSheet();
}
} else if (id == R.id.nav_share) {
//share the app intent
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey! look what I found from play store.\nDownload cool & amazing wallpapers for your device from this app, "+getResources().getString(R.string.app_name)+", among various categories.\n\nCheck this out:\n"+StaticUtils.playStoreUrlDefault+getPackageName()+"\nDownload now:)");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share app through..."));
} else if (id == R.id.nav_rate) {
//rate the app intent
Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
}
} else if (id == R.id.nav_about) {
//about page
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,3); //3 for about fragment
i.putExtra(StaticUtils.KEY_SEARCH_DATA,"About");
startActivity(i);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void playLogoAudio(){
Log.d(TAG, "playLogoAudio: playing logo audio");
View headerView = navigationView.getHeaderView(0);
ImageView drawerLogo = headerView.findViewById(R.id.imageLogo);
drawerLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.hello);
mediaPlayer.start();
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public void onSearchStateChanged(boolean enabled) {
if (enabled){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
}else{
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
Log.d(TAG, "onSearchConfirmed: confirmed search: "+text);
Intent i = new Intent(this,SecondActivity.class);
i.putExtra(StaticUtils.KEY_FRAG_ID,1);
i.putExtra(StaticUtils.KEY_SEARCH_DATA,String.valueOf(text));
if(new NetworkUtils(getApplicationContext()).checkConnection(drawer)) { //start intent if network connected
StaticUtils.recentSearchesList.add(String.valueOf(text)); //adds the query to the recents list
if (StaticUtils.recentSearchesList.size()>20){
StaticUtils.recentSearchesList.remove(0);
}
SearchFragment.updateAdapter(this,StaticUtils.recentSearchesList);
searchBar.setText(""); //removes the search query
startActivity(i);
}
}
#Override
public void onButtonClicked(int buttonCode) {
Log.d(TAG, "onButtonClicked: search interface button clicked: "+buttonCode);
switch (buttonCode){
case MaterialSearchBar.BUTTON_NAVIGATION:
drawer.openDrawer(GravityCompat.START);
break;
case MaterialSearchBar.BUTTON_BACK:
searchBar.disableSearch();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {}
public void saveArrayList(ArrayList<String> list, String key){
Log.d(TAG, "saveArrayList: saving recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
Log.d(TAG, "getArrayList: getting saved recent searchList data");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
#Override
protected void onPause() {
super.onPause();
//Saving arraylist when activity gets paused
saveArrayList(StaticUtils.recentSearchesList,StaticUtils.KEY_LIST_PREFERENCCES);
}
public void searchEvents(){
Log.d(TAG, "searchEvents: managing the search events");
searchBar.addTextChangeListener(new TextWatcher() {
ArrayList<String> tempList = new ArrayList<>();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d(TAG, "beforeTextChanged: clearing the list");
if (!tempList.isEmpty()){
tempList.clear();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(TAG, "onTextChanged: changing search query");
for (String string : StaticUtils.recentSearchesList) {
if (s.length() > 0) {
if (string.matches("(?i)(" + s + ").*")) {
tempList.add(string);
SearchFragment.updateAdapter(getApplicationContext(), tempList);
}
}else{
SearchFragment.updateAdapter(getApplicationContext(), StaticUtils.recentSearchesList);
}
}
}
#Override
public void afterTextChanged(Editable s) {}
});
}
#Override
protected void onResume() {
super.onResume();
navigationView.setCheckedItem(R.id.nav_home);
if (!permissionsGranted(this)){ //checking and requesting permissions
grantPermissionBottomSheet();
}
}
public static boolean permissionsGranted(Context context) {
Log.d(TAG, "checkPermissions: checking if permissions granted.");
int result;
listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(context,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
//if all/some permissions not granted
return listPermissionsNeeded.isEmpty();
}
public static void requestPermissions(Activity activity){
Log.d(TAG, "requestPermissions: requesting permissions.");
ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), StaticUtils.MULTIPLE_PERMISSIONS);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: action when permission granted or denied");
if (requestCode == StaticUtils.MULTIPLE_PERMISSIONS) {
if (grantResults.length <= 0) {
// no permissions granted.
showPermissionDialog();
}
}
}
public void showPermissionDialog(){
Log.d(TAG, "showPermissionDialog: requesting permissions");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
builder.setMessage("You'll not be able to use this app properly without these permissions.");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//re-requesting permissions
requestPermissions(MainActivity.this);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
I would suggest some kind of different flow.
Most apps have something called a "Splash screen" (usually with a logo, sometimes kind of a progress bar).
what you can do is create a splash activity, - if there is internet call your MainActiviy, otherwise call another activity NetworkErrorActivity with the XML you want.

Rate my app dialog when the user want to exit my app

I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit" now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picselct);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
photoGrid = (GridView) findViewById(R.id.albumGrid);
Model.LoadModel();
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
photoGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.e("FolderName", Model.GetbyId(position+1).FolderName);
String FolderName=Model.GetbyId(position+1).FolderName;
String CategoryName=Model.GetbyId(position+1).Name;
Intent i=new Intent(PicSelect.this,PicItem.class);
i.putExtra("Folder", FolderName);
i.putExtra("Category", CategoryName);
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.rateapp:
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
case R.id.moreapp:
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
`
finaly if anyone know how to style the text thank you for your help
.setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=[your package name]"));
startActivity(i);
}
})
This will give you a negative option that says Rate App that when clicked opens the market to your app.
Improve your app with this snippet in onBackPressed():
if(isTaskRoot()) {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}else {
super.onBackPressed();
}

Call another Activity in Main Activity

sorry my question is may be very simple for all of you. But I am new and need solution for it. If you can help me for solve it.
I have one quote application which have function for check new quote from server in main activity, its checking with server on loading Main Activity that there new quotes available or not and if available its opening one popup window for go setting activity for download new quotes, and if user press setting button than its taking user to setting activity. I need some changes in it. I want automatic download new quotes from main activity without go setting activity. both activity are like below
Thanks
public class MainActivity extends Activity {
SharedPreferences mSharedPreferences;
//String qotdId;
private AdView mAdView;
private InterstitialAd mInterstitial;
public static boolean active;
DAO db;
String siteUrl, updatesUrl;
int lastAuthor, lastQuote;
private ConnectionDetector cd;
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
active = true;
}
#Override
protected void onStop() {
super.onStop();
active = false;
}
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
/* Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
*/
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
db = new DAO(this);
db.open();
cd = new ConnectionDetector(MainActivity.this);
siteUrl = getResources().getString(R.string.siteUrl);
updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);
if (cd.isConnectingToInternet()) {
// Internet Connection is not present
Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);
startService(checkUpdates);
}
// generateKeyHash();
final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
quotes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 1);
intent.putExtra("itemSelected", 0);
startActivity(intent);
}
});
final ImageButton authors = (ImageButton) findViewById(R.id.authors);
authors.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AuthorsActivity.class);
startActivity(intent);
}
});
final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
favorites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 2);
startActivity(intent);
}
});
final ImageButton settings = (ImageButton) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
}
});
}
}
And my other activity
public class SettingsActivity extends PreferenceActivity {
static final int TIME_DIALOG_ID = 999;
private AdView mAdView;
private InterstitialAd mInterstitial;
private static final String MY_PREFERENCES = "my_preferences";
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
}
#Override
protected void onStop() {
//unregisterReceiver(receiver);
super.onStop();
}
// ==========================================================================================================//
DAO db;
// Progress dialog
ProgressDialog pDialog;
PreferenceScreen preferenceScreen;
private static SharedPreferences mSharedPreferences;
UpdateClass update;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
Preference more, rate, about, check, share,status,background, progress = null;
PreferenceCategory socialsCategory;
private MyDownloadReceiver receiver;
// ==============================================================================
//////////////////// First Load /////////////////
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
//TWITTER_CONSUMER_KEY = getResources().getString(
// R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(
// R.string.TWITTER_CONSUMER_SECRET);
//TWITTER_CALLBACK_URL = "oauth://"
// + getApplicationContext().getPackageName()
// + ".SettingsActivity";
//uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
addPreferencesFromResource(R.layout.settings);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
check = (Preference) findPreference("check");
about = (Preference) findPreference("about");
more = (Preference) findPreference("more");
rate = (Preference) findPreference("rate");
status = (Preference) findPreference("status");
share = (Preference) findPreference("share");
background = (Preference) findPreference("background");
socialsCategory = (PreferenceCategory) findPreference("socials");
preferenceScreen = getPreferenceScreen();
check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
update = new UpdateClass(SettingsActivity.this);
update.handleUpdates();
//if (mInterstitial.isLoaded()) {
// mInterstitial.show();
//}
return false;
}
});
// ==============================================================================
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsActivity.this,
AboutActivity.class);
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
return false;
}
});
// ==============================================================================
background
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.equals(true)) {
db.updateSetting("background", "1");
} else {
db.updateSetting("background", "0");
}
return true;
}
});
// ==============================================================================
// ==============================================================================
rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindishayari2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String developerName = "karopass";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));
}
return true;
}
});
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
});
// ==============================================================================
status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindi_status_2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MyDownloadReceiver();
registerReceiver(receiver, filter);
}
void showProgressBar() {
progress = new MyProgressBarPreference(this);
preferenceScreen.addPreference(progress);
}
void setDownloadProgress(int percent) {
if (progress != null) {
((MyProgressBarPreference)progress).setProgress(percent);
((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
}
}
void hideProgressBar()
{
if (progress != null)
preferenceScreen.removePreference(progress);
}
public class MyDownloadReceiver extends BroadcastReceiver {
public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";
public static final int INITIALIZE = 0x001;
public static final int DOWNLOAD = 0x002;
public static final int FINISH = 0x003;
public static final String EXTRA_STATUS = "status";
public static final String EXTRA_PERCENT = "percent";
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_STATUS, -1);
Log.d("DESOLF", "receive broadcast : " + status);
switch(status) {
case INITIALIZE:
showProgressBar();
break;
case DOWNLOAD:
int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
setDownloadProgress(percent);
break;
case FINISH:
hideProgressBar();
//Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
break;
default:
}
}
}
public class MyProgressBarPreference extends Preference {
public MyProgressBarPreference(Context context) {
super(context);
}
public MyProgressBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ImageView mStatusIcon;
private ProgressBar mProgressBar;
private TextView mStatusText ;
private int lastReqProgress=-1;
private int lastReqMax=-1;
private String lastLabel;
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View myLayout=li.inflate(R.layout.download_progress, null, false);
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
mStatusIcon.startAnimation(anim);
mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
mStatusText=(TextView) myLayout.findViewById(R.id.status_text);
mStatusIcon.setImageResource(R.drawable.rotate);
mProgressBar.setProgress(0);
mStatusText.setText(0 + "%");
return myLayout;
}
public void setIcon(int resId) {
mStatusIcon.setImageResource(resId);
}
public void setProgress(int value){
if (mProgressBar!=null){
mProgressBar.setProgress(value);
} else {
lastReqProgress=value;
}
}
public void setMax(int value){
if (mProgressBar!=null){
int savedprogress=mProgressBar.getProgress();
mProgressBar.setMax(0);
mProgressBar.setMax(value);
mProgressBar.setProgress(savedprogress);
} else {
lastReqMax=value;
}
}
public void setLabel(String text){
if (lastLabel!=null){
mStatusText.setText(text);
} else {
lastLabel=text;
}
}
}
}
You can try this code:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Don't forget to add your Second Activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="SecondActivity"/>
Android Page

Android App opening url in browser not through webview in application

I need to open the url inside the webview not the browser yet it always opens it in the browser Any reason why? I;ve added code to the WebView which I thought would do it. It has been working fine and now it opens in the browser for some reason
WebView Code:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context = MapActivity.this;
private boolean isPageLoadedComplete = false;
private Timer myTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
ActivityHelper activityHelper = new ActivityHelper(this);
activityHelper.setTitleTextSize(R.string.Store_Locator, false);
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.canGoBack();
Uri uri = Uri.parse(urlString);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
myTimer = new Timer();
//Start this timer when you create you task
myTimer.schedule(new loaderTask(), 20000);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
#Override
public void onLoadResource(WebView view, String url) {
// Check to see if there is a progress dialog
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
progressDialog.setCancelable(true);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
#Override
public void onPageFinished(WebView view, String url) {
isPageLoadedComplete = true;
View mapHeight = (View) findViewById(R.id.webview);
int height = mapHeight.getHeight();
Log.d("map height","map height" + height);
// Page is done loading;
// hide the progress dialog and show the webview
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
AlertDialog();
}
});
}
public class loaderTask extends TimerTask {
public void run() {
System.out.println("Times Up");
if(isPageLoadedComplete){
Log.d(TAG, "The page loaded perfectly");
myTimer.cancel();
}else{
Log.d(TAG, "The page was not loaded correctly");
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
AlertDialog();
}
});
}
}
}
public void AlertDialog(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(R.string.Search_Error);
alertDialog.setMessage(R.string.Failure_to_create_URL_connection);
alertDialog.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}Fsie

Webview shows white blank page in Ice Cream Sandwitch

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 :)

Categories