I want to show WebView in Android on which I want to play video from html video tag.
I write the code for doing this and video is played automatically i.e. without press any button video is automatically started.
But, I want WebView is only shown when video is ready to play.
Please see my code and tell me what piece of code I have to write so that when video buffers completes then WebView will become visible and video started automatically.
I added a button on GUI when click on that button this method will be called.
public void onShowInlineVideoButton(View view) {
//webView.setVisibility(View.VISIBLE);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
int SDK_INT = android.os.Build.VERSION.SDK_INT;
System.out.println("!!!!!!! SDK_INT is: " + SDK_INT);
if (SDK_INT > 16) {
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
}
webView.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
#Override public void onPageFinished(WebView view, String url) {
System.out.println("!!!!!!!!!! In onPageFinished method...");
webView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })");
webView.setVisibility(View.VISIBLE);
}
// #Override public void onLoadResource(WebView view, String url) { System.out.println("!!!!!!!onLoadResource" + webView.getProgress()); if(webView.getProgress() == 100 ) webView.setVisibility(View.VISIBLE);}
});
//webView.setWebChromeClient(new WebChromeClient());
// load the customURL with the URL of the page you want to display
String pageURL = "file:///android_asset/videotag.html";
webView.loadUrl(pageURL);
//webView.setVisibility(View.VISIBLE);
//webView.setPublicationId(publisherIdForNativeAds);
//webView.loadAd();
}
Here is an xml file for activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="#+id/showInlineVideo"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:onClick="onShowInlineVideoButton"
android:text="#string/showInlineVideoButtonLabel"
android:textSize="14sp" />
<WebView
android:id="#+id/inlineVideo"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Here is an html file for video named as "videotag.html"
<!DOCTYPE html>
<html>
<body>
<a href="http://www.globe.com.ph/mylifestyleplan" target="_bla">
<video id="video" controls preload="metadata" autoplay buffered height="245" width="335" webkit-playsinline="webkit-playsinline" class="videoPlayer">
<source src="https://s3.amazonaws.com/silverpushcdn/debTest/videoplayback.mp4" type='video/mp4' />
</video>
</a>
</body>
</html>
Now please help me that what should I do so that WebView only visible when video is ready to start, until it will be remain invisible.
Related
I find this more difficult than working on an XML file. How do I block spaces in the text input of an alert dialog? For example, how does it work because I didn't find much information about this on the internet. Thank you
private void RequestNewGroup()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
groupNameField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
{
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
}
else
{
CreateNewGroup(groupName);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.show();
}
I find this more difficult than working on an XML file.
You could (and probably should) create custom dialogs that have their own view/XML file.
To do this, extend DialogFragment:
public class MyDialog extends DialogFragment {
EditText editText;
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// get your custom layout
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_custom_layout, null);
builder.setView(view).setCancelable(false);
editText = view.findViewById(R.id.editText);
// add your code here
}
}
XML (R.layout.my_custom_layout):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="foo"
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
android:inputType="textFilter" />
</androidx.constraintlayout.widget.ConstraintLayout>
and in MainActivity:
public void openDialog(Context context) {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(), "myDialog");
}
also check Android disable space only for Edittext to disable space from XML and
https://www.youtube.com/watch?v=ARezg1D9Zd0&t=446s&ab_channel=CodinginFlow for a more in depth tutorial on custom dialogs and how to send and recieve info from them.
Below I attached the code to be executed with webview.
NOTE: JAVASCRIPT SHOULD BE ENABLED
ANYONE HELP ME TO RUN THIS HTML STRING IN WEBVIEW
<!DOCTYPE html>
<html>
<body>
<!-- Markup for HTML (Factors in Placement and Enrollment of Primary
Care Patientsin YMCA's Diabetes Prevention Program, Bronx, New
York,2010-2015) --><div class='rid_08184eef_309335'
data-apiroot='//tools.cdc.gov/api' data-mediatype='html'
data-mediaid='309335' data-stripscripts='true' data-stripanchors='false'
data-stripimages='false' data-stripcomments='true'
data-stripstyles='true' data-cssclasses='syndicate' data-ids=''
data-xpath='' data-oe='utf-8' data-of='xhtml' data-ns='cdc'
data-postprocess='' data-nw='true' data-iframe='true'
data-cdc-widget='syndicationIframe'
data-apiembedsrc='skins/larry//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js'
data-iframeembedsrc='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'></div><script
src='skins/larry//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js'
></script><noscript>You need javascript enabled to view this content or go to <a href='skins/larry//tools.cdc.gov/api/v2/resources/media/309335/noscript'>source URL</a>.</noscript>
</body>
</html>
I followed this link for basic setup. Nothing helped
BELOW I ATTACHED MY JAVA CODE
public class WebtestActivity extends Activity {
WebView webtest;
final Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.webviewtesting);
webtest=(WebView)findViewById(R.id.webtest);
String htmlString = "<!-- Markup for HTML (How to Prevent Cancer or Find It Early) --><div class=\"rid_ec9fb40c_123238\" data-apiroot=\"//tools.cdc.gov/api\" data-mediatype=\"HTML\" data-mediaid=\"123238\" data-stripscripts=\"false\" data-stripanchors=\"false\" data-stripimages=\"false\" data-stripcomments=\"false\" data-stripstyles=\"false\" data-cssclasses=\"syndicate\" data-ids=\"\" data-xpath=\"\" data-oe=\"UTF-8\" data-of=\"XHTML\" data-ns=\"\" data-postprocess=\"\" data-nw=\"true\" data-iframe=\"true\" data-cdc-widget=\"syndicationIframe\" data-apiembedsrc=\"//tools.cdc.gov/api/embed/html/js/embed-2.0.3.js\" data-iframeembedsrc=\"//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js\" data-font=\"\"></div><script src='//tools.cdc.gov/TemplatePackage/contrib/widgets/tp-widget-external-loader.js' ></script><noscript>You need javascript enabled to view this content or go to <a href='//tools.cdc.gov/api/v2/resources/media/123238/noscript'>source URL</a>.</noscript>";
webtest.getSettings().setJavaScriptEnabled(true);
webtest.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webtest.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
Log.d("des===",description);
Log.d("failingUrl===",failingUrl);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.d("shouldlLoading===",url);
view.loadUrl(url);
return true;
}
});
webtest.loadData(htmlString, "text/html", null);
}
}
try this code. If you are learning, use official docs > WebView
String htmlString = "<html><body>Your text.</body></html>";
browser.getSettings().setJavaScriptEnabled(true);
browser.loadData(htmlString, "text/html", null);
Your code working fine. I attached screenshot
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class Settings_Menu extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_menu);
TurnSoundOff();
}
private void TurnSoundOff() {
final CheckBox TurnSoundOff= (CheckBox) findViewById(R.id.StartupsoundoffBox);
TurnSoundOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (TurnSoundOff.isChecked()){
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile); //errors at .create since I can't use a class
mp.stop();
}else{
mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile);
mp.start();
}
}});
}
}
Here is my code, i'm just trying to shutoff or turn on a designated audio file from when the app opens. I have the Checkbox or toggle button in another activity. I'm using media player and some what new to android coding thanks for reading. I setup a settings action from tapping overflow then the settings button to go to activity and I want the audio shutoff or back on in the MainActivity.xml when the check is click from the settings activity. thanks again for reading and help in advance. It errors at .create since I can't use a class
You have to do this using shared preferences . It is very simple.. Instead of making an activity make a preference screen.. Follow these steps..:-
1) Go to resource folder.
2) make a new folder called 'xml'.
3) In xml folder you created make a xml file called 'prefs.xml'.
in that sdd the following code..:-
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:defaultValue="false"
android:key="music"
android:summary="Tick to listen the music"
android:title="Intro Music" >
</CheckBoxPreference>
</PreferenceScreen>
now go to ur activity that plays the song..
ourSong = MediaPlayer.create(Splash.this, R.raw.splash_sound);
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean music = getPrefs.getBoolean("music", true);
if (music == true)
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
};
timer.start();
this thread is used for the timer of your activity.. if u dnt want any timer delete the thread.. the value in the sleep(****) is the time in miliseconds.
add this function also to stop the song after the activity is changed..
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
To get the overflow menu :-
1)make a new folder called menu
2)make a xml file.. add the following code.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:title="Preferences"
android:id="#+id/preferences" />
<item android:title="Exit"
android:id="#+id/exit" />
</menu>
In you actvity add the following code..So that prefernece could be called
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.preferences:
Intent b = new Intent("com.example.code.PREFS");
//instead of 'com.example.code' write your package name
startActivity(b);
break;
case R.id.exit:
finish();
break;
}
return false;
}
And in the end make a class called Prefs and add the following code..
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
Finally add the class in the manifest.. code for that..
<activity
android:name="com.example.code.Prefs"
android:label="Preferences" >
<intent-filter>
<action android:name="com.example.code.PREFS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
your action name should be same as u mentioned in the intent in onMenuItemSelected()...
This would do the trick... :) Peace...
In my application i need to search the phone contact numbers and I want to select a number and I want to save that number and after that once I click, send button message should go to that number. Here am using more than two activities and am searching a contacts inside of one such activity..
please any one can help me..thanks in advance..
Here is my code.
public class SearchNum extends Activity {
private TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchnum);
resultText = (TextView)findViewById(R.id.searchViewResult);
setupSearchView();
}
private void setupSearchView() {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) findViewById(R.id.searchView);
SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
searchView.setSearchableInfo(searchableInfo);
}
#Override
protected void onNewIntent(Intent intent) {
if (ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED.equals(intent.getAction())) {
//handles suggestion clicked query
String displayName = getDisplayNameForContact(intent);
resultText.setText(displayName);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
resultText.setText("should search for query: '" + query + "'...");
}
}
private String getDisplayNameForContact(Intent intent) {
Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
phoneCursor.moveToFirst();
int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String name = phoneCursor.getString(idDisplayName);
phoneCursor.close();
return name;
}
}
and my xml file for search view is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SearchNum" >
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</SearchView>
<TextView
android:id="#+id/searchViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:text="#string/hello_world" />
</RelativeLayout>
Then my searchable file in xml folder is
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/findContact"
android:hint="#string/findContact"
android:includeInGlobalSearch="true"
android:queryAfterZeroResults="true"
android:searchMode="queryRewriteFromText"
android:searchSettingsDescription="#string/findContact"
android:searchSuggestAuthority="com.android.contacts"
android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
android:searchSuggestIntentData="content://com.android.contacts/contacts/lookup" >
<!-- allow green action key for search-bar and per-suggestion clicks -->
<actionkey
android:keycode="KEYCODE_CALL"
android:queryActionMsg="call"
android:suggestActionMsg="call" />
</searchable>
and also i have taken permission in my manifest file
<uses-permission android:name="android.permission.READ_CONTACTS" />
in activity i put
<action android:name="android.intent.action.SEARCH" />
and also here is my metadata
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
You also need to add to your manifest file:
android:launchMode="singleTop"
Link: http://looksok.wordpress.com/2013/06/15/android-searchview-tutorial-edittext-with-phone-contacts-search-and-autosuggestion/
I am working on a very simple player written in MXML+ActionScript whose functions are exported to be called by a simple Javascript in an HTML page.
Both codes are provided below.
For the mp3 "path" all is working perfectly for playing, pausing, resuming and stopping...
For the m4a "path", starting is working well, stopping too but pausing is bugging
After having started an m4a, when I clicked on "pause" it rightly stops the stream.
But when I am clicking back on the button to resume, it does not start again at all
Does anybody know where is the problem?
Is the fact that I'm using just a simple Apache Web Server and not a real Flash Streaming server the reason why it does not work?
Thanks in advance for your help.
The MXML+ActionScript 3
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="callBacks()">
<mx:Script>
<![CDATA[
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.external.ExternalInterface;
public var playingChannel:SoundChannel;
public var playingSound:Sound;
public var pausePosition:int=0;
public var playingUrl:String="";
public var codec:String="";
public var playingStream:NetStream;
public function playSound(url:String):void {
if (playingUrl!=url) {
if (playingUrl!="") {
stopSound();
}
playingUrl=url;
codec=playingUrl.substring(playingUrl.length-3);
if (codec=="m4a") {
var mySound:SoundTransform;
var connect_nc:NetConnection = new NetConnection();
connect_nc.connect(null);
playingStream=new NetStream(connect_nc);
playingStream.play(url);
}
else if (codec=="mp3") {
playingSound=new Sound(new URLRequest(url));
playingChannel=playingSound.play();
}
}
else {
if (codec=="m4a")
playingStream.pause();
else
playingChannel=playingSound.play(pausePosition);
}
}
public function pauseSound():void {
if (codec=="m4a")
playingStream.pause();
else if (codec=="mp3") {
pausePosition=playingChannel.position;
playingChannel.stop();
}
}
public function stopSound():void {
if (codec=="m4a")
playingStream.close();
else if (codec=="mp3") {
pausePosition=0;
playingChannel.stop();
}
playingUrl="";
}
public function callBacks():void {
ExternalInterface.addCallback("play",playSound);
ExternalInterface.addCallback("pause",pauseSound);
ExternalInterface.addCallback("stop",stopSound);
}
]]>
</mx:Script>
</mx:Application>
and the basic HTML+Javascript
<html>
<head>
<script src='jquery.js'></script>
<script>
function play() {
//alert('clicked');
var url=$("#url").val();
var k=url.substring(url.length-3);
fromFlash('testFlash').play(url);
var b=document.getElementById('pp');
b.setAttribute('src','pauseButton.jpg');
b.setAttribute('onclick','pause()');
}
function pause() {
fromFlash('testFlash').pause();
var b=document.getElementById('pp');
b.setAttribute('src','playButton.jpg');
b.setAttribute('onclick','play()');
}
function stop() {
fromFlash('testFlash').stop();
var b=document.getElementById('pp');
b.setAttribute('src','playButton.jpg');
b.setAttribute('onclick','play()');
}
function fromFlash(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
</script>
</head>
<body>
<object id="testFlash" width="0" height="0">
<param name="movie" value="player.swf"></param>
<param name="allowFullScreen" value="true"></param>
<embed name="testFlash" src="player.swf" type="application/x-shockwave-flash" allowfullscreen="true" width="0" height="0">
</embed>
</object>
<input id="url"/>
<span><img id="pp" src="playButton.jpg" onclick="play()"/></span>
<span><img src="stopButton.jpg" onclick="stop()"/></span>
</body>
</html>
I believe you want to call pause() again to resume, not play().
According to the NetStream documentation, the pause() method is used for both pause and resume.