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
Related
I've been stuck in a situation and i need some help over here. There are many articles on this topic here but none of them answered my question. I want to implement onBackPressed() in fragments and show dialog box which shows to exit the application or not. Any help would be appreciated.
LoginFragment.java
public class LoginFragment extends Fragment {
public static final String TAG = LoginFragment.class.getSimpleName();
private EditText mEtEmail;
private EditText mEtPassword;
private Button mBtLogin;
private TextView mTvRegister;
private TextView mTvForgotPassword;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private ProgressBar mProgressBar;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mSubscriptions = new CompositeSubscription();
initViews(view);
initSharedPreferences();
return view;
}
private void initViews(View v) {
mEtEmail = v.findViewById(R.id.et_email);
mEtPassword = v.findViewById(R.id.et_password);
mBtLogin = v.findViewById(R.id.btn_login);
mTiEmail = v.findViewById(R.id.ti_email);
mTiPassword = v.findViewById(R.id.ti_password);
mProgressBar = v.findViewById(R.id.progress);
mTvRegister = v.findViewById(R.id.tv_register);
mTvForgotPassword = v.findViewById(R.id.tv_forgot_password);
mBtLogin.setOnClickListener(view -> login());
mTvRegister.setOnClickListener(view -> goToRegister());
mTvForgotPassword.setOnClickListener(view -> showDialog());
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
private void login() {
setError();
String email = mEtEmail.getText().toString();
String password = mEtPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
mProgressBar.setVisibility(View.VISIBLE);
} else {
showSnackBarMessage("Enter Valid Details !");
}
}
private void setError() {
mTiEmail.setError(null);
mTiPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email, password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
mProgressBar.setVisibility(View.GONE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
mEtEmail.setText(null);
mEtPassword.setText(null);
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
private void handleError(Throwable error) {
mProgressBar.setVisibility(View.GONE);
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("No Internet Connection!");
}
}
private void showSnackBarMessage(String message) {
if (getView() != null) {
Snackbar.make(getView(),message,Snackbar.LENGTH_SHORT).show();
}
}
private void goToRegister(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
RegisterFragment fragment = new RegisterFragment();
ft.replace(R.id.fragmentFrame,fragment,RegisterFragment.TAG);
ft.addToBackStack(null).commit();
}
private void showDialog(){
ResetPasswordDialog fragment = new ResetPasswordDialog();
fragment.show(getFragmentManager(), ResetPasswordDialog.TAG);
}
#Override
public void onDestroy() {
super.onDestroy();
mSubscriptions.unsubscribe();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ResetPasswordDialog.Listener {
public static final String TAG = MainActivity.class.getSimpleName();
private LoginFragment mLoginFragment;
private ResetPasswordDialog mResetPasswordDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
loadFragment();
}
}
private void loadFragment() {
if (mLoginFragment == null) {
mLoginFragment = new LoginFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame, mLoginFragment, LoginFragment.TAG).commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String data = intent.getData().getLastPathSegment();
Log.d(TAG, "onNewIntent: " + data);
mResetPasswordDialog = (ResetPasswordDialog) getFragmentManager().findFragmentByTag(ResetPasswordDialog.TAG);
if (mResetPasswordDialog != null)
mResetPasswordDialog.setToken(data);
}
#Override
public void onPasswordReset(String message) {
showSnackBarMessage(message);
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.activity_main), message, Snackbar.LENGTH_SHORT).show();
}
}
In My Login Fragment, I want to show a dialog box "Do you want to exit the application or not". On Yes it dismiss the current fragment and end the activity otherwise it'll remain active. Help please!
You can even try this way
MainActivity.java
#Override
public void onBackPressed() {
if (getFragmentManager() != null && getFragmentManager().getBackStackEntryCount() >= 1) {
String fragmentTag = getFragmentManager().findFragmentById(R.id.frame_container).getTag();
if(fragmentTag.equals(LoginFragment.getTag())){
// show Dialog code
}else{
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Add this code in your main activity so that when login fragment is added and you click backpress, then on first if the fragment is added to fragment transaction, then first it finds the fragment and check if its tag is equals to the login fragment tag. Then if both tag matches, then you can show your exit alert dialog.
Android team has prepared a new way of handling the back button pressed on Fragments for us, so you should check this out. It's called OnBackPressedDispatcher.
You need to register OnBackPressedCallback to the fragment where do you want to intercept back button pressed. You can do it like this inside of the Fragment:
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
//show exit dialog
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
I need to make an app that sends an SMS message after showing a progress bar in increments of 10. I have the action bar set up and I think I should use AsyncTask? The user is inputing number and message into the main activity, and that's where I have the SendSMS method set up, not sure how to make this work so that it forwards to AsyncTask and calls on that method there.
public class MainActivity extends AppCompatActivity {
private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
private static final String SMS_SENT = "SMS_SENT";
private static final String SMS_DELIVERED= "SMS_DELIVERED";
private EditText etPoruka;
private EditText etBroj;
private ProgressDialog progressDialog;
private Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
private void initWidgets() {
etPoruka = findViewById(R.id.etPoruka);
etBroj = findViewById(R.id.etBroj);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
MyAsyncTask<Void, Void, Void> updateTask = new MyAsyncTask<Void, Void, Void>(context);
updateTask.execute();
break;
case R.id.action_sent:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
// BROADCAST RECEIVER ??
break;
case R.id.action_received:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
//BROADCAST RECEIVER ??
//BOUND SERVICE
break;
case R.id.action_exit:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Close app");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
}
public void sendSMS() {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(etBroj.getText().toString(),null,etPoruka.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
ASYNCTASK
public class MyAsyncTask extends
AsyncTask {
private final String DIALOG_MESSAGE = "Sending message";
private ProgressDialog mDialog = null;
private void setDialog(Context context) {
this.mDialog = new ProgressDialog(context);
this.mDialog.setMessage(DIALOG_MESSAGE);
this.mDialog.setCancelable(false);
}
public MyAsyncTask(Context context) {
this.setDialog(context);
}
#Override
protected void onPreExecute() {
this.mDialog.show();
}
#Override
protected Result doInBackground(Params... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Result result) {
if (this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} }
You can create an Interface and implement in your MainActivity.
For More Details Please check these answers:
how do i send data back from onPostExecute in an AsyncTask?
How to pass data from an asynchronous task to an activity that called it?
This is my code it is working fine it scans Qr/Barcode, but I want scanned data to insert in fire-base database. This app is connected with fire-base and using ML kit for barcode scanning. This app also has login signup connected with fire-base auth and scanner app. but I don't know how to push scanned data in fire-base realtime database in android studio.
public class MainActivity extends AppCompatActivity {
View view;
CameraView camera_view;
boolean isDetected= false;
Button btn_start_again;
private static final String TAG = "MainActivity";
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Dexter.withActivity(this)
.withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setupCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
private void setupCamera()
{
btn_start_again= (Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(isDetected);
btn_start_again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
camera_view = (CameraView)findViewById(R.id.cameraView);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame)
{
processImage(getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image){
if(!isDetected)
{
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){
if (firebaseVisionBarcodes.size()>0)
{
isDetected = true;
btn_start_again.setEnabled(isDetected);
for(FirebaseVisionBarcode item: firebaseVisionBarcodes)
{
int value_type = item.getValueType();
switch (value_type)
{
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
//start browser intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
break;
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name: ")
.append(item.getContactInfo().getName().getFormattedName())
.append("\n")
.append("Address: ")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email: ")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
break;
}
}
}
}
private void createDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame){
byte[] data= frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize() .getHeight())
.setWidth(frame.getSize() .getWidth())
//.setRotation(frame.getRotation())
.build();
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}
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
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();
}
});