Chromecast button not visible in android - java

I am following the code lab tutorial.
My Gradle file looks like this
dependencies {
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:mediarouter-v7:25.0.0'}
This is my CastOptionsProvider class
public class CastOptionsProvider implements OptionsProvider {
#Override
public CastOptions getCastOptions(Context context) {
return new CastOptions.Builder()
.setReceiverApplicationId(context.getString(R.string.chromecast_app_id))
.build();
}
#Override
public List<SessionProvider> getAdditionalSessionProviders(Context context) {
return null;
}}
This is the menu xml file
<menu 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">
<item
android:id="#+id/media_route_menu_item"
android:title="#string/media_route_menu_title"
app:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
app:showAsAction="always" /></menu>
And this is my OnCreateOptionsMenu method in MainActivity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item);
return true;
}
And this in the manifest file
<meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.mypackage.CastOptionsProvider" />
I have followed the codelab tutorial to its exact form, copy and pasted everything while changing those variable which needs to be changed.
My application and the chromecast device are connected to the same network. The Chromecast button appears in the Youtube app but not on my app. What am I missing ?
Thanks

It might be an invalid app_id.
You might try replacing your chromecast_app_id string resource with the app_id string resource value from the sample project.
(Right now, it's 4F8B3483. See: https://github.com/googlecast/CastVideos-android/blob/master/res/values/strings.xml).
Believe it or not, switching to that value made the cast icon visible in my app.

If everything is done properly, you just need to restart cast device (it does not work with your app_id without restarting after registration).

Check in Google Cast SDK Developer Console if your Application ID is correct and status is Published.
When publish your Application ID, restart your Chromecast device.
For testing purposes, you can use CC1AD845 or 4F8B3483 as Application ID. These are from Google sample apps.

Adding another answer as the accepted answer did nothing for me. The issue happened to me only when building a proguarded version of my app.
I had to add a couple lines to my proguard file (essentially all of the classes referenced by xml as mentioned here: https://stackoverflow.com/a/24578823/1048847)
-keep class com.your.package.CastOptionsProvider { *; }
// I have a custom MediaRouteActionProvider but this may need to be
// android.support.v7.app.MediaRouteActionProvider in the case of OP
-keep class com.your.package.MediaRouteActionProvider { *; }

you are missing attribute icon here
<menu 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">
<item
android:id="#+id/media_route_menu_item"
android:title="#string/media_route_menu_title"
android:icon="#drawable/chromebutton" app:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
app:showAsAction="always" /></menu>

Related

android pre populate preferences dynamically

I would like to check programmatically whether an sd card is installed, and if yes, give the user the choice to switch between external and internal storage.
I have my other static settings organized inside a preferences.xml.
It seems that I have to rewrite all the settings of the xml file in code if I start to work with preferences more dynamically.
Or is there an option to enhance the preferences from the xml with preferences from code which get used just once needed?
Thanks
Add this to manifest for install app on sd card if is possible:
android:installLocation="preferExternal">
To verify is sd card writable and readable use this method:
private boolean isExternalStorageWritable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}
To get folder of appfiles on sdCard (externalStorageVolumes[0] is primary folder):
File[] externalStorageVolumes =
ContextCompat.getExternalFilesDirs(getApplicationContext(), null);
Oficial documentation
I found out myself, it looks a bit clumsy, but it works.
Once again: My problem is that I have certain setting options pre configured in an xml file as described here:
Preferences with XML
Here is my preferences.xml:
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="#string/download_header">
<SwitchPreferenceCompat
app:key="dl_background"
app:title="#string/background_behaviour"
app:defaultValue="false"/>
<ListPreference
app:title="#string/dl_qual"
app:defaultValue="#string/low_qual"
app:key="dl_qual"
app:entries="#array/dl_qual_arry"
app:entryValues="#array/dl_qual_arry"/>
</PreferenceCategory>
<PreferenceCategory app:title="#string/tc_header">
<SwitchPreferenceCompat
app:key="tc_installed"
app:title="#string/tc_behaviour"
app:defaultValue="false"/>
<ListPreference
app:title="#string/dl_dir_root"
app:key="dl_dir_root"/>
</PreferenceCategory>
</PreferenceScreen>
Here you can define arrays which map to ListPrefrence objects.
Each option list is then populated from a resource xml file holding the actual list entries.
I used this approach for the first ListPreference "dl_qual" above.
This is the resource.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="dl_qual_arry">
<item>Higher quality (128kbps)</item>
<item>Lower quality (64kbps)</item>
</string-array>
</resources>
But then I had the idea to insert a ListPreference where the values of the options list are only known at runtime.
This is my second ListPreference above "dl_dir_root".
I was too lazy to rewrite (and read how to do it in advance) the complete settings activity from code.
So I ended up with this SettingsFragment inside my SettingsActivity:
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
//First, lets check whether we have initialized preferences already
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String selectedDir = prefs.getString("dl_dir_root", "INIT");
setPreferencesFromResource(R.xml.root_preferences, rootKey);
PreferenceScreen root = getPreferenceScreen();
ListPreference dlDirRoot = root.findPreference("dl_dir_root");
CharSequence[] arryValues = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
CharSequence[] arryEntrys = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
dlDirRoot.setEntries(arryEntrys);
dlDirRoot.setEntryValues(arryValues);
if(selectedDir.equals("INIT")) {
//Initialize value/index
dlDirRoot.setDefaultValue(arryValues[0]);
dlDirRoot.setValueIndex(0);
}
else{
//Position at already selected value/index
dlDirRoot.setDefaultValue(selectedDir);
dlDirRoot.setValue(selectedDir);
dlDirRoot.setValueIndex(dlDirRoot.findIndexOfValue(selectedDir));
}
}
}
The pre defined xml is applied first, then the ListPreference object for "dl_dir_root" is acessed and the options are added:
ListPreference dlDirRoot = root.findPreference("dl_dir_root");
CharSequence[] arryValues = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
CharSequence[] arryEntrys = BBCWorldServiceDownloaderUtils.getStoragePaths(getContext());
dlDirRoot.setEntries(arryEntrys);
dlDirRoot.setEntryValues(arryValues);
The rest is checking/keeping state between the calls to the activity.
If anyone knows of a more elegant way, I would be curious.
Best
Matthias

How to add a menu folder to the res folder of an android studio project

I want to add a menu to my Android project and I created a menu folder inside the res folder, but got the error:
cannot resolve symbol 'menu'.
I was following an Android developers tutorial Menus | Android Developers
I will leave a screenshot of my project here:
project
And here is the code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
game_menu.xml:
game_menu.xml
Try clean and after rebuild project, in menu Build on Android Studio.
Is that how you created it? you should try.
Res -> new -> Android Resource Directory -> Resource Type (Menu) -> Ok
Try to put it into one line of code like: getMenuInflater().inflate(R.menu.game_menu, menu);
First of all it is nicer coding I belive and that way we can be sure that the MenuInfalter is working. I have looked it up in my project and it is the same way there + working. If that does not help please share your game_menu.xml.
Use this code in your game_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="75"
android:title="my menu Item!"
app:showAsAction="never"/>

Chromecast crashes when cast icon clicked

I am trying to add Chromecast function to my Android app. I've been following the code lab tutorial from Google's cast dev page, I've managed to get it working using there test app. But when I try to copy the code to from the test app to my own app i get the option to connect to my test device. But once it connects it just resets my Chromecast, then disconnects again.
This is my CastOptionProvider Class
public final class CastOptionsProvider implements OptionsProvider {
#Override
public CastOptions getCastOptions(Context context) {
return new CastOptions.Builder()
.setReceiverApplicationId(context.getString(R.string.app_id))
.build();
}
public List<SessionProvider> getAdditionalSessionProviders(Context context) {
return null;
}
}
This is my activities xml that I want to have Chromecast support
<RelativeLayout 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"
tools:context="studios.p9p.harrop99.p9pdocumentaries.Actual_Genres.Taboo">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
The activities java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_taboo);
setupActionBar();
mCastContext = CastContext.getSharedInstance(this);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Taboo");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private MenuItem mediaRouteMenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.browse, menu);
mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item);
return true;
}
I know the tutorial is not complete yet but by this point in the tutorial I can connect to my test casting device and a casting logo appears on my screen. But in my own app it resets my Chromecast and does not actually connect. Also I have a Google speaker that in the tutorial it will offer to connect to this. It does not even show in my app.
Here is a link to the tutorial I'm following.
Edit
Do I need a custom receiver? If so where would I upload it to?
fixed this issue, it was that i needed a custom Reciever adding to my server. it was crashing because i was trying to use the basic a basic Reciever from Googles dev page.
the basic reciever only allows for mp4 streams and direct video sources. But because im using youtube streams i had to use a package from github. this included a custom reciever to upload.
the basic tutorial i used can be found here
chromecast tutorial
and his github can be found here
github package and sample app
i also want to thank Pier Francescosoffritti for all the hard work he has put in to this

Blank screen on video expand in android

I created a sample app using JieCao player for android and it works perfectly fine both on portrait and landscape mode (on pressing expand button). But when I tried to integrate the same for the another app that I'm creating I get a black screen on pressing the video expand button but the audio is playing in the background. Couldn't get the reason why this is happening !! I have explained the code that I'm working on below :
Mainactivity.java
jcVideoPlayerStandard = (JCVideoPlayerStandard) findViewById(R.id.custom_videoplayer_standard);
jcVideoPlayerStandard.setUp("http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4","");
ImageLoader.getInstance().displayImage("http://p.qpic.cn/videoyun/0/2449_bfbbfa3cea8f11e5aac3db03cda99974_1/640",jcVideoPlayerStandard.thumbImageView);
activity_main.xml
<fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
android:id="#+id/custom_videoplayer_standard"
android:layout_width="match_parent"
android:layout_marginTop="55dp"
android:layout_height="250dp" />
And a separate java file that I include in AndroidManifest file though I'm pretty much sure it has nothing to do with the error. Here is the code :
public class VideoApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
LeakCanary.install(this);
initUniversalImageLoader();
}
private void initUniversalImageLoader() {
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getApplicationContext());
config.threadPriority(Thread.NORM_PRIORITY - 2);
config.denyCacheImageMultipleSizesInMemory();
config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
config.tasksProcessingOrder(QueueProcessingType.LIFO);
config.writeDebugLogs(); // Remove for releaseAllVideos app
config.defaultDisplayImageOptions(getDefaultDisplayImageOption());
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config.build());
}
public static DisplayImageOptions getDefaultDisplayImageOption() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(new ColorDrawable(Color.parseColor("#f0f0f0")))
.resetViewBeforeLoading(true)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(500))
.build();
return options;
}}
If there is anything else needed please let me know, I just want to know where I am going wrong.
Note : People with higher reputation please create a tag "JieCao-player" which might be useful while creating a question related to this category. As I don't have enough reputation, kindly do the needful.
Just need to make sure that "android:hardwareAccelerated" is set to true in all the activities in Manifest file. By doing so the problem got resolved.

Android onCreateOptionsMenu is not displaying

In my android activity, i removed the Action Bar by using this Theme
<style name="Theme.NoTitle" parent="#android:style/Theme.NoTitleBar"></style>
but my problem is “onCreateOptionsMenu” is not display, I tried this method to create
that pls see
private void getOverflowMenu()
{
try
{
ViewConfiguration config = ViewConfiguration.get(Home.this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null)
{
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config , false);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
in this “onCreateOptionsMenu” is not displaying. please help me
but it displaying in Samsung
Because: in Samsung mobile has its own hardware menu button, but not in nexus etc
please see the image
finally i got the answer
in my AndroidManifest.xml i just removed this line
android:targetSdkVersion="18"
If you don't have action bar and neither a menu button (on most devices) where do you want to display your menu??
The easiest way is to use PopupMenu. Add a button somewhere in your layout and on the click even add the PopupMenu (Dropdown menu). If you want to use it for devices starting Android 2.1 use a Support Library.
You have HERE the android documentation about PopupMenu.
From SDK Manager you can download and see the support library v7 sample which includes PopupMenuHelper.
Hope it helps. Good Luck!

Categories