This is code I got online for sending mail in android studio using the Gmail API, but I need to fixed sender and mail I need to send at the same time as like sender hazem#gmail.com and receiver will be hazem11#gmail.com without showing which account I need to send mail and which mail I should have added to send.
public class MainActivity extends AppCompatActivity {
FloatingActionButton sendFabButton;
EditText edtToAddress, edtSubject, edtMessage, edtAttachmentData;
Toolbar toolbar;
GoogleAccountCredential mCredential;
ProgressDialog mProgress;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = {
GmailScopes.GMAIL_LABELS,
GmailScopes.GMAIL_COMPOSE,
GmailScopes.GMAIL_INSERT,
GmailScopes.GMAIL_MODIFY,
GmailScopes.GMAIL_READONLY,
GmailScopes.MAIL_GOOGLE_COM
};
private InternetDetector internetDetector;
private final int SELECT_PHOTO = 1;
public String fileName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
findViewById(R.id.attachment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Utils.checkPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECT_PHOTO);
}
}
});
findViewById(R.id.changeAccount).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Utils.checkPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
startActivityForResult(mCredential.newChooseAccountIntent(), Utils.REQUEST_ACCOUNT_PICKER);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECT_PHOTO);
}
}
});
sendFabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getResultsFromApi(view);
}
});
}
Related
I am trying to use peerjs in android vie webview, but the problem is it not working, when I debugged and tried different approaches I got to know that normal js functions work with no problem, the problem only when I call a function which includes peerjs
permissions i took in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
MAINACTIVITY
here are two buttons 1 calls to simple js function named callJs and other one calls peerjs function named testweb
public class MainActivity extends AppCompatActivity {
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
// Setting Allowed JS Bullet Window
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onPermissionRequest(PermissionRequest request) {
request.grant(request.getResources());
}
});
webView.addJavascriptInterface(new JavaScriptInterface(this),"AndroidFunction");
webView.loadUrl("file:///android_asset/webViewTest.html");
Button webTest1 = findViewById(R.id.webTest1);
//calls normal js function
webTest1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.post(new Runnable() {
#Override
public void run() {
webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
}
});
}
});
}
});
Button webTest2 = findViewById(R.id.webTest2);
//calls js function with peerjs
webTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webView.post(new Runnable() {
#Override
public void run() {
webView.evaluateJavascript("javascript:testWeb()", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
}
});
}
});
}
});
}
JAVASCRIPTINTERFACE
public class JavaScriptInterface {
MainActivity mainActivity;
public JavaScriptInterface(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#JavascriptInterface
public void showToast(String toast){
Toast.makeText(mainActivity, toast, Toast.LENGTH_LONG).show();
}
js functions
<script src="./peerjs.js"></script>
<script type="text/javascript">
function callJS() {
AndroidFunction.showToast("Toast From javascript");
alert("Android Called JS Of callJS Method");
}
function testWeb() {
alert("testWeb Method called");
var peer = new Peer(1234, {
host: "192.168.****",
port: 8000,
path: "/strange",
});
peer.on("open", () => {
AndroidFunction.showToast("Toast From testWebPeer");
});
}
</script>
I am trying to develop an android app, I am using Retrofit2 for handling all my network stuff and communication with the server.
I have a main activity and I also have login activity.
I am initializing the Retrofit on the main activity and I am trying to send the login activity the retrofit initialized interface and then things got hard.
According to a little research I can't just send the retrofit stuff to the new activity with '.putextra(...)' function.
I will be happy to get some help with that.
My Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final UserService userConnection;
userConnection = ApiUtils.getUserService();
Toolbar toolBar = (Toolbar)findViewById(R.id.app_bar);
toolBar.setTitle("Welcome #PlaceHolder");
setSupportActionBar(toolBar);
startActivity(new Intent(MainActivity.this,LoginActivity.class));
// Intent i = new Intent(this, LoginActivity.class);
// i.putExtra("userConnection", (Serializable) userConnection);
// startActivity(i);
ScrollView feed = (ScrollView)findViewById(R.id.feedView);
//LinearLayOut Setup
LinearLayout feed1 = (LinearLayout)findViewById(R.id.feed);
Feed feed2 = new Feed(this,feed1);
feed1 = feed2.getFeed();
//***************************************************//
Call call = userConnection.getResponse();
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
ResObj resObj = (ResObj) response.body();
if(resObj.getpostID().equals("12Aa")){
//login start main activity
//Intent intent = new Intent(MainActivity.this, MainActivity.class);
// intent.putExtra("username", "tomer");
//startActivity(intent);
Log.e("Error is blabla: ","Yes");
} else {
Toast.makeText(MainActivity.this, "The username or password is incorrect", Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",response.toString());
}
Log.e("Error is blabla: ",response.message().toString());
} else {
Toast.makeText(MainActivity.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",response.toString());
}
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",t.toString());
}
});
}
}
My Login Activity:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = getIntent();
final UserService userConnection =(UserService)getIntent.getSerializableExtra("userConnection");
Button loginBtn = (Button)findViewById(R.id.loginButton);
EditText emailBox = (EditText) findViewById(R.id.emailBox);
EditText passBox = (EditText) findViewById(R.id.passBox);
final String email = emailBox.getText().toString();
final String password = passBox.getText().toString();
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Call login = userConnection.login(email,password);
login.enqueue(new Callback() {
#Override
public void onResponse(Call call, retrofit2.Response response) {
if(response.isSuccessful())
{
ResObj resObj = (ResObj) response.body();
if(resObj.loginStatus().equals("connected")){
Log.e("Login Status: ","Success");
finish();
}
else {
Log.e("Login Status: ","Wrong Password or Email");
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.e("Login Status: ","Faild To Recieve Server Message");
}
});
}
});
Button registerBtn = (Button)findViewById(R.id.registerButton);
registerBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
}
}
The UserService Interface:
public interface UserService{
#GET("/testDB")
Call<ResObj> getResponse(
);
#POST("/login")
Call<ResObj> login(#Query("userEmail") String userEmail,
#Query("userPassword") String userPassword);
}
The ApiUtiles Class:
public class ApiUtils {
public static final String BASE_URL = "http://**.***.***.***:****";
public static UserService getUserService(){
return RetrofitClient.getClient(BASE_URL).create(UserService.class);
}
}
I will be happy to get solution or guide of how to send retrofit interfaces between activities :)
I was facing problem for calling android Admob interstitial from webview. I could not get any proper solution. Finally I figured out the solution to call the interstitial for javascript. Look into the below answer.
Solution for the above problem
Import all the required packages.
public class MainActivity extends AppCompatActivity {
WebView myWevView;
public InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
myWevView =(WebView)findViewById(R.id.myWevView);
WebSettings ws= myWevView.getSettings();
ws.setJavaScriptEnabled(true);
ws.setDomStorageEnabled(true);
myWevView.getSettings().setUseWideViewPort(true);
myWevView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWevView.setWebViewClient(new WebViewClient());
myWevView.setWebChromeClient(new WebChromeClient());
myWevView.getSettings().setBuiltInZoomControls(true);
myWevView.loadUrl("file:///android_asset/index.html");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
}
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
public void displayLoadedAd(){
runOnUiThread(new Runnable() {
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
else
Toast.makeText(getApplicationContext(), "Ad not loded", Toast.LENGTH_SHORT).show();
}
});
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showAdFromJs(){
Toast.makeText(mContext, "Loading Ad", Toast.LENGTH_SHORT).show();
displayLoadedAd();
}
}
//Controlling navigation
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (myWevView.canGoBack()) {
myWevView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
calling from javascript
$("#btn1").click(function(){
Android.showAdFromJs();
});
I used this without the javascript call like this:
#Override
public void onAdLoaded(){
displayLoadedAd();
}
You would need to lower the number of interstitial ads to your pref. in your admob console.
I would like to show direct this content without press the buttons. Can someone help me? I'm new to the programming world.
In the below have the complete content, if you want to analyze better.
http://www.androidbegin.com/tutorial/android-basic-jsoup-tutorial/
public class MainActivity extends Activity {
// URL Address
String url = "http://www.androidbegin.com";
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the Buttons in activity_main.xml
Button titlebutton = (Button) findViewById(R.id.titlebutton);
// Capture button click
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new Title().execute();
}
});
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(url).get();
// Get the html document title
title = document.title();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
TextView txttitle = (TextView) findViewById(R.id.titletxt);
txttitle.setText(title);
mProgressDialog.dismiss();
}
}
}
Put following code directly under the line setContentView...
new Title().execute();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview1);
web.setWebChromeClient(new MyWebChromeClient());
web.addJavascriptInterface(new DemoJavaScriptInterface(), "temp_1");
web.loadUrl("file:///android_asset/temp_1.html");
}
}
final class DemoJavaScriptInterface {
private Handler mHandler = new Handler();
WebView web;
DemoJavaScriptInterface() {
}
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
web.loadUrl("javascript:init();");
}
});
}
}
final class MyWebChromeClient extends WebChromeClient {
private static final String LOG_TAG = "WebViewDemo";
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.e(LOG_TAG, message);
result.confirm();
return true;
}
}
Try to write this line
web = (WebView) findViewById(R.id.webview1);
web.setWebChromeClient(new MyWebChromeClient());
web.getSettings().setJavaScriptEnabled(true);
web.addJavascriptInterface(new DemoJavaScriptInterface(), "temp_1");
web.loadUrl("file:///android_asset/temp_1.html");
[2]: Both Elements are coming from html file ,when going to click on "Click It" nothing happens instead of displaying xml data that i want