error cs0103 the name does not exist in the current context - facebook

I have my game with facebook invite integrated using unity3d. When switched to Android, everything works fine but when I switch to WebGL, I get the following error:
error CS0103: The name `LoggedSuccefull' does not exist in the current context
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.SceneManagement;
#if FACEBOOK
using Facebook.Unity;
#endif
public class FacebookManager : MonoBehaviour {
private bool LoginEnable;
public GameObject facebookButton;
//1.3.3
private string lastResponse = string.Empty;
public static string userID;
public static List<FriendData> Friends = new List<FriendData> ();
public bool logged;
protected string LastResponse {
get {
return this.lastResponse;
}
set {
this.lastResponse = value;
}
}
private string status = "Ready";
protected string Status {
get {
return this.status;
}
set {
this.status = value;
}
}
bool loginForSharing;
public static FacebookManager THIS;
void Awake () {
if (THIS == null)
THIS = this;
else if (THIS != this)
Destroy (gameObject);
DontDestroyOnLoad (this);
}
void OnEnable () {
#if PLAYG
NetworkManager.OnLoginEvent += GetUserName;
#endif
}
void OnLevelWasLoaded () {
if (logged && SceneManager.GetActiveScene ().name == "game")
LoggedSuccefull ();
}
void OnDisable () {
#if PLAYG
NetworkManager.OnLoginEvent -= GetUserName;
#endif
}
#if PLAYG || GAMESPARKS
public FriendData GetCurrentUserAsFriend () {
//code
}
#endif
#region FaceBook_stuff
#if FACEBOOK
public void CallFBInit () {
Debug.Log ("init facebook");
FB.Init (OnInitComplete, OnHideUnity);
}
private void OnInitComplete () {
Debug.Log ("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
if (FB.IsLoggedIn) {//1.3
CallFBLogin ();
}
}
private void OnHideUnity (bool isGameShown) {
Debug.Log ("Is game showing? " + isGameShown);
}
void OnGUI () {
if (LoginEnable) {
CallFBLogin ();
LoginEnable = false;
}
}
public void CallFBLogin () {
Debug.Log ("login");
FB.LogInWithReadPermissions (new List<string> () { "public_profile", "email", "user_friends" }, this.HandleResult);
}
public void CallFBLoginForPublish () {
FB.LogInWithPublishPermissions (new List<string> () { "publish_actions" }, this.HandleResult);
}
public void CallInvite () {
this.Status = "Logged FB.AppEvent";
FB.Mobile.AppInvite (new Uri ("//URI Here"), callback: this.HandleResultInvite);
// NOTE !! create your app link here https://developers.facebook.com/quickstarts/?platform=app-links-host
}
protected void HandleResultInvite (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
public void CallFBLogout () {
FB.LogOut ();
//code
}
public void Share () {
if (!FB.IsLoggedIn) {
//code
}
protected void HandleResult (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// this.LastResponseTexture = null;
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
LoggedSuccefull ();//1.3
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
void LoggedSuccefull () {//1.3
logged = true;
facebookButton.SetActive (false);//1.3.3
if (PlayerPrefs.GetInt ("Facebook_Logged") == 0) {
GameObject rewardPopup = Instantiate (Resources.Load ("Reward")) as GameObject;
rewardPopup.transform.GetChild (0).GetComponent<RewardIcon> ().SetIconSprite (0);
InitScript.Instance.AddGems (10);
}
PlayerPrefs.SetInt ("Facebook_Logged", 1);
PlayerPrefs.Save ();
if (SceneManager.GetActiveScene ().name != "game")
return;
//Debug.Log(result.RawResult);
userID = AccessToken.CurrentAccessToken.UserId;
GetPicture (AccessToken.CurrentAccessToken.UserId);
}
void GetUserName () {
FB.API ("/me?fields=first_name", HttpMethod.GET, GettingNameCallback);
}
private void GettingNameCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error)) {
IDictionary dict = result.ResultDictionary as IDictionary;
string fbname = dict ["first_name"].ToString ();
#endif
}
}
void GetPicture (string id) {
FB.API ("/" + id + "/picture", HttpMethod.GET, this.ProfilePhotoCallback);
}
private void ProfilePhotoCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error) && result.Texture != null) {
Sprite sprite = new Sprite ();
sprite = Sprite.Create (result.Texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
InitScript.profilePic = sprite;
#endif
}
}
public void SaveScores () {
//code
}
public void ReadScores () {
FB.API ("/me/objects/object", HttpMethod.GET, APICallBack);
}
public void GetFriendsPicture () {
FB.API ("me/friends?fields=picture", HttpMethod.GET, RequestFriendsCallback);
}
private void RequestFriendsCallback (IGraphResult result) {
if (!string.IsNullOrEmpty (result.RawResult)) {
// Debug.Log (result.RawResult);
//code
}
//}
}
//print(firstGroup["id"] + " " + firstGroup["title"]);
}
//this.gamerGroupCurrentGroup = (string)firstGroup["id"];
}
}
if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log (result.Error);
}
}
}
public void GetPictureByURL (string url, FriendData friend) {
StartCoroutine (GetPictureCor (url, friend));
}
IEnumerator GetPictureCor (string url, FriendData friend) {
Sprite sprite = new Sprite ();
WWW www = new WWW (url);
yield return www;
sprite = Sprite.Create (www.texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
friend.picture = sprite;
// print ("get picture for " + url);
}
public void APICallBack (IGraphResult result) {
Debug.Log (result);
}
#endif
#endregion
}
public class FriendData {
public string userID;
public string FacebookID;
public Sprite picture;
public int level;
public GameObject avatar;
}
Any help would be highly appreciated

Related

Admob for Unity app does not show add

I have a problem with admob for unity app, I used documentation to add admob, I used video tutorial from youtube and I tried demo app (hello world from admob), but the result is the same, ad banners does not appear in my apps, as for, if use interstitials, when I try to show it, my app crashes. However, in console there is a dummy message.
my code
using GoogleMobileAds.Api;
public class AdMobManager : MonoBehaviour {
private BannerView bannerView;
[SerializeField] private string appID = "";
[SerializeField] private string bannerID = "";
[SerializeField] private string regularAD = "";
private void Awake(){
MobileAds.Initialize(appID);
}
public void OnClickShowBanner() {
this.RequestBanner();
}
public void OnClickShowAd() {
this.RequestReqularAd();
}
private void RequestReqularAd() {
InterstitialAd AD = new InterstitialAd(regularAD);
AdRequest request = new AdRequest.Builder().Build();
AD.LoadAd(request);
}
public void RequestBanner() {
bannerView = new BannerView(bannerID, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
}
}
You can use this simple code for admob banner. some time it takes time to display banner ad but this script worked fine.
Source
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
private BannerView bannerView;
public void Start()
{
this.RequestBanner();
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
string adUnitId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
bannerView.LoadAd(request);
}
}
Source code available https://github.com/unity-plugins/Unity-Admob/blob/master/AdmobPluginRes/admobdemo.cs
using UnityEngine;
using admob;
public class admobdemo : MonoBehaviour {
Admob ad;
string appID="";
string bannerID="";
string interstitialID="";
string videoID="";
string nativeBannerID = "";
void Start () {
Debug.Log("start unity demo-------------");
initAdmob();
}
void Update () {
if (Input.GetKeyUp (KeyCode.Escape)) {
Debug.Log(KeyCode.Escape+"-----------------");
}
}
void initAdmob()
{
#if UNITY_IOS
appID="ca-app-pub-3940256099942544~1458002511";
bannerID="ca-app-pub-3940256099942544/2934735716";
interstitialID="ca-app-pub-3940256099942544/4411468910";
videoID="ca-app-pub-3940256099942544/1712485313";
nativeBannerID = "ca-app-pub-3940256099942544/3986624511";
#elif UNITY_ANDROID
appID="ca-app-pub-3940256099942544~3347511713";
bannerID="ca-app-pub-3940256099942544/6300978111";
interstitialID="ca-app-pub-3940256099942544/1033173712";
videoID="ca-app-pub-3940256099942544/5224354917";
nativeBannerID = "ca-app-pub-3940256099942544/2247696110";
#endif
AdProperties adProperties = new AdProperties();
adProperties.isTesting = true;
ad = Admob.Instance();
ad.bannerEventHandler += onBannerEvent;
ad.interstitialEventHandler += onInterstitialEvent;
ad.rewardedVideoEventHandler += onRewardedVideoEvent;
ad.nativeBannerEventHandler += onNativeBannerEvent;
ad.initSDK(appID,adProperties);//reqired,adProperties can been null
}
void OnGUI(){
if (GUI.Button(new Rect(120, 0, 100, 60), "showInterstitial"))
{
Debug.Log("touch inst button -------------");
if (ad.isInterstitialReady())
{
ad.showInterstitial();
}
else
{
ad.loadInterstitial(interstitialID);
}
}
if (GUI.Button(new Rect(240, 0, 100, 60), "showRewardVideo"))
{
Debug.Log("touch video button -------------");
if (ad.isRewardedVideoReady())
{
ad.showRewardedVideo();
}
else
{
ad.loadRewardedVideo(videoID);
}
}
if (GUI.Button(new Rect(0, 100, 100, 60), "showbanner"))
{
Admob.Instance().showBannerRelative(bannerID,AdSize.SMART_BANNER, AdPosition.BOTTOM_CENTER);
}
if (GUI.Button(new Rect(120, 100, 100, 60), "showbannerABS"))
{
Admob.Instance().showBannerAbsolute(bannerID,AdSize.BANNER, 20, 220,"mybanner");
}
if (GUI.Button(new Rect(240, 100, 100, 60), "removebanner"))
{
Admob.Instance().removeBanner();
Admob.Instance().removeBanner("mybanner");
}
if (GUI.Button(new Rect(0, 200, 100, 60), "showNative"))
{
Admob.Instance().showNativeBannerRelative(nativeBannerID,new AdSize(320,280), AdPosition.BOTTOM_CENTER);
}
if (GUI.Button(new Rect(120, 200, 100, 60), "showNativeABS"))
{
Admob.Instance().showNativeBannerAbsolute(nativeBannerID,new AdSize(-1,132), 0, 300);
}
if (GUI.Button(new Rect(240, 200, 100, 60), "removeNative"))
{
Admob.Instance().removeNativeBanner();
}
}
void onInterstitialEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onAdLoaded)
{
Admob.Instance().showInterstitial();
}
}
void onBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobBannerEvent---" + eventName + " " + msg);
}
void onRewardedVideoEvent(string eventName, string msg)
{
Debug.Log("handler onRewardedVideoEvent---" + eventName + " rewarded: " + msg);
}
void onNativeBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobNativeBannerEvent---" + eventName + " " + msg);
}
}

unity piano game trouble with playback of recorded notes

i have a piano app in unity and i am using an ArrayList to add notes and then playing it back and it workes mostly but the playback method since it activates when playMode is true, it continues on a loop, i need to know how i can use an if statement to check if all the recorded notes have been played and if they have then the loop should break. i really need help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NotePlay: MonoBehaviour
{
public Button record, play;
public bool recordMode = false;
public bool playMode = false;
Animator anim;
public AudioClip noteA;
public AudioClip noteB;
public AudioClip noteC;
public AudioClip noteD;
public AudioClip noteE;
public AudioClip noteF;
public AudioClip noteG;
public AudioSource audio;
public int count = 0;
// Use this for initialization
public ArrayList notes;
void Start()
{
anim = gameObject.GetComponent<Animator>();
audio = GetComponent<AudioSource>();
notes = new ArrayList();
Button rec = record.GetComponent<Button>();
Button pl = play.GetComponent<Button>();
record.onClick.AddListener(()=>{ recordMode = !recordMode; });
play.onClick.AddListener(() => { playMode = !playMode; recordMode =
false; });
}
void Playback()
{
bool flag = true;
for (int i = 0; i < notes.Count && flag; i++)
{
char c = (char)notes[i];
System.Threading.Thread.Sleep(1000);
PlayNote(c);
print(c);
// i want the recorded notes to only play once
if ()
{
}
}
}
void PlayNote(char note)
{
if (note == 'a')
{
//anim.SetTrigger("A");
GameObject.Find("Sphere_A").GetComponent<AudioSource>
().PlayOneShot(noteA);
GameObject.Find("Sphere_A").GetComponent<Animator>
().SetTrigger("A");
print("a");
}
if (note == 'b')
{
//anim.SetTrigger("B");
GameObject.Find("Sphere_B").GetComponent<AudioSource>
().PlayOneShot(noteB);
GameObject.Find("Sphere_B").GetComponent<Animator>
().SetTrigger("B");
print("b");
}
if (note == 'c')
{
///anim.SetTrigger("C");
GameObject.Find("Sphere_C").GetComponent<AudioSource>
().PlayOneShot(noteC);
GameObject.Find("Sphere_C").GetComponent<Animator>
().SetTrigger("C");
}
if (note == 'd')
{
//anim.SetTrigger("D");
GameObject.Find("Sphere_D").GetComponent<AudioSource>
().PlayOneShot(noteD);
GameObject.Find("Sphere_D").GetComponent<Animator>
().SetTrigger("D");
}
if (note == 'e')
{
//anim.SetTrigger("E");
GameObject.Find("Sphere_E").GetComponent<AudioSource>
().PlayOneShot(noteE);
GameObject.Find("Sphere_E").GetComponent<Animator>
().SetTrigger("E");
}
else if (note == 'f')
{
// anim.SetTrigger("F");
GameObject.Find("Sphere_F").GetComponent<AudioSource>
().PlayOneShot(noteF);
GameObject.Find("Sphere_F").GetComponent<Animator>
().SetTrigger("F");
}
else if (note == 'g')
{
//anim.SetTrigger("G");
GameObject.Find("Sphere_G").GetComponent<AudioSource>
().PlayOneShot(noteG);
GameObject.Find("Sphere_G").GetComponent<Animator>
().SetTrigger("G");
}
}
// Update is called once per frame
void Update()
{
if (recordMode == true)
{
if (Input.GetKeyDown(KeyCode.A)) {notes.Add('a'); PlayNote('a'); }
if (Input.GetKeyDown(KeyCode.B)) {notes.Add('b'); PlayNote('b'); }
if (Input.GetKeyDown(KeyCode.C)) {notes.Add('c'); PlayNote('c'); }
if (Input.GetKeyDown(KeyCode.D)) {notes.Add('d'); PlayNote('d'); }
if (Input.GetKeyDown(KeyCode.E)) {notes.Add('e'); PlayNote('e'); }
if (Input.GetKeyDown(KeyCode.F)) {notes.Add('f'); PlayNote('f'); }
if (Input.GetKeyDown(KeyCode.G)) {notes.Add('g'); PlayNote('g'); }
}
else
{
if (Input.GetKeyDown(KeyCode.A)) { PlayNote('a'); }
if (Input.GetKeyDown(KeyCode.B)) { PlayNote('b'); }
if (Input.GetKeyDown(KeyCode.C)) { PlayNote('c'); }
if (Input.GetKeyDown(KeyCode.D)) { PlayNote('d'); }
if (Input.GetKeyDown(KeyCode.E)) { PlayNote('e'); }
if (Input.GetKeyDown(KeyCode.F)) { PlayNote('f'); }
if (Input.GetKeyDown(KeyCode.G)) { PlayNote('g'); }
}
if (playMode == true )
{
Playback();
}
}
}
You may want to specify that the AudioSource don't have to loop the sound. Add this line to your Start method :
void Start()
{
anim = gameObject.GetComponent<Animator>();
audio = GetComponent<AudioSource>();
audio.loop = false; // <--------------- HERE
notes = new ArrayList();
Button rec = record.GetComponent<Button>();
Button pl = play.GetComponent<Button>();
record.onClick.AddListener(()=>{ recordMode = !recordMode; });
play.onClick.AddListener(() => { playMode = !playMode; recordMode = false; });
}
You can either do this in code as above or directly in the inspector of your AudioSource. I think the default value of the loop property is set to true, that's why it's looping when you play a note.

Camera 2 api full screen not to stretch

private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
private static final long DELAY = 1000;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
int num = 1;
List<VideoModel> videoList;
private Handler customHandler = new Handler();
private static final String TAG = "RecordVideoActivity";
private String videoName;
static {
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
static {
INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
}
private AutoFitTextureView mTextureView;
private ImageButton mRecordButton;
private ImageView mDots;
private ImageButton mCheckPoint;
private CameraDevice mCameraDevice;
private CameraCaptureSession mPreviewSession;
private TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
openCamera(width, height);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
configureTransform(width, height);
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
private Size mPreviewSize;
private Size mVideoSize;
private MediaRecorder mMediaRecorder;
private boolean mIsRecordingVideo;
private HandlerThread mBackgroundThread;
private Handler mBackgroundHandler;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice cameraDevice) {
mCameraDevice = cameraDevice;
startPreview();
mCameraOpenCloseLock.release();
if (null != mTextureView) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int error) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
finish();
}
};
private Integer mSensorOrientation;
private String mNextVideoAbsolutePath;
private CaptureRequest.Builder mPreviewBuilder;
private CameraManager manager;
private String cameraId;
private boolean isFlashSupported;
private ImageButton flashButton;
private ImageButton switchCamera;
private ImageButton revertVideo;
public static final String CAMERA_BACK = "0";
private TextView mChronometer;
private String flashOpt;
private long lastSavedTime;
private String prepend;
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
return size;
}
}
Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
// Collect the supported resolutions that are at least as big as the preview Surface
List<Size> bigEnough = new ArrayList<>();
int w = aspectRatio.getWidth();
int h = aspectRatio.getHeight();
for (Size option : choices) {
if (option.getHeight() == option.getWidth() * h / w &&
option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
// Pick the smallest of those, assuming we found any
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
Log.e(TAG, "Couldn't find any suitable preview size");
return choices[0];
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera2_video_image);
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (dir.isDirectory()) {
deleteDirectory(dir);
}
videoList = new ArrayList<>();
mTextureView = findViewById(R.id.textureView);
mRecordButton = findViewById(R.id.videoOnlineImageButton);
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint = findViewById(R.id.checkPoint);
mCheckPoint.setVisibility(View.GONE);
mDots = findViewById(R.id.dot);
mRecordButton.setOnClickListener(this);
flashButton = findViewById(R.id.flashVideo);
switchCamera = findViewById(R.id.switchVideo);
revertVideo = findViewById(R.id.revertVideo);
revertVideo.setVisibility(View.GONE);
mChronometer = findViewById(R.id.chronometer);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
flashOpt = prefs.getString(getString(R.string.flash_option), getString(R.string.auto));
if (flashOpt.equals(getString(R.string.flash_off)))
flashButton.setImageResource(R.drawable.flash_auto);
else if (flashOpt.equals(getString(R.string.flash_on)))
flashButton.setImageResource(R.drawable.flash_on);
else
flashButton.setImageResource(R.drawable.flash_off);
findViewById(R.id.checkPoint).setOnClickListener(this);
findViewById(R.id.flashVideo).setOnClickListener(this);
findViewById(R.id.switchVideo).setOnClickListener(this);
findViewById(R.id.revertVideo).setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
startBackgroundThread();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if(mIsRecordingVideo)
mRecordButton.setImageResource(R.drawable.ic_video_stop);
else
mRecordButton.setImageResource(R.drawable.ic_video);
mCheckPoint.setEnabled(true);
startTime=SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
#Override
public void onPause() {
closeCamera();
mCheckPoint.setEnabled(false);
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
stopBackgroundThread();
super.onPause();
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int hour = mins / 60;
mChronometer.setText("" + hour + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.videoOnlineImageButton: {
if (mIsRecordingVideo) {
mDots.setVisibility(View.GONE);
mChronometer.setVisibility(View.GONE);
switchCamera.setVisibility(View.VISIBLE);
mCheckPoint.setVisibility(View.GONE);
stopRecordingVideo();
Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mNextVideoAbsolutePath)));
sendBroadcast(mediaStoreUpdateIntent);
} else {
mCheckPoint.setVisibility(View.VISIBLE);
switchCamera.setVisibility(View.GONE);
mChronometer.setVisibility(View.VISIBLE);
mDots.setVisibility(View.VISIBLE);
startRecordingVideo();
}
break;
}
case R.id.switchVideo: {
facingCamera = !facingCamera;
closeCamera();
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
break;
}
case R.id.flashVideo: {
if (onFlashCheck()) {
CameraCharacteristics cameraCharacteristics = null;
try {
cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean available = cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
isFlashSupported = available == null ? false : available;
switchFlash();
}
break;
}
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#SuppressLint("MissingPermission")
private void openCamera(int width, int height) {
final Activity activity = this;
if (null == activity || activity.isFinishing()) {
return;
}
manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
Log.d(TAG, "tryAcquire");
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
cameraId = manager.getCameraIdList()[1];
if (facingCamera) {
cameraId = manager.getCameraIdList()[1];
flashButton.setVisibility(View.GONE);
} else {
cameraId = manager.getCameraIdList()[0];
flashButton.setVisibility(View.VISIBLE);
}
// Choose the sizes for camera preview and video recording
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (map == null) {
throw new RuntimeException("Cannot get available preview/video sizes");
}
mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, mVideoSize);
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
}
configureTransform(width, height);
mMediaRecorder = new MediaRecorder();
manager.openCamera(cameraId, mStateCallback, null);
} catch (CameraAccessException e) {
Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
activity.finish();
} catch (NullPointerException e) {
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.");
}
}
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
closePreviewSession();
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mMediaRecorder) {
mMediaRecorder.release();
mMediaRecorder = null;
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.");
} finally {
mCameraOpenCloseLock.release();
}
}
private void startPreview() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
Surface previewSurface = new Surface(texture);
mPreviewBuilder.addTarget(previewSurface);
mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
mPreviewSession = session;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (null == mCameraDevice) {
return;
}
try {
setUpCaptureRequestBuilder(mPreviewBuilder);
HandlerThread thread = new HandlerThread("CameraPreview");
thread.start();
mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
if (onFlashCheck()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.VISIBLE);
}
});
if (flashOpt.equals(getString(R.string.auto)))
builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
else if (flashOpt.equals(getString(R.string.flash_off)))
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
else
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
} else
runOnUiThread(new Runnable() {
#Override
public void run() {
flashButton.setVisibility(View.GONE);
}
});
}
private void configureTransform(int viewWidth, int viewHeight) {
if (null == mTextureView || null == mPreviewSize) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / mPreviewSize.getHeight(),
(float) viewWidth / mPreviewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
mTextureView.setTransform(matrix);
}
private void setUpMediaRecorder() throws IOException {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
File file = getVideoFilePath(this);
mNextVideoAbsolutePath = file.getAbsolutePath();
videoName = file.getName();
mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
mMediaRecorder.setVideoEncodingBitRate(10000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
switch (mSensorOrientation) {
case SENSOR_ORIENTATION_DEFAULT_DEGREES:
mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
break;
case SENSOR_ORIENTATION_INVERSE_DEGREES:
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
break;
}
mMediaRecorder.prepare();
}
private File getVideoFilePath(Context context) {
File appDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) + File.separator + AppConstants.APPDIRRECORDING);
if (!appDir.isDirectory()) {
appDir.mkdirs();
}
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "VIDEO_" + timestamp + ".mp4";
File videoFile = null;
try {
videoFile = File.createTempFile(prepend, ".mp4", appDir);
} catch (IOException e) {
e.printStackTrace();
}
return videoFile;
}
private void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
return;
}
try {
closePreviewSession();
setUpMediaRecorder();
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
List<Surface> surfaces = new ArrayList<>();
// Set up Surface for the camera preview
Surface previewSurface = new Surface(texture);
surfaces.add(previewSurface);
mPreviewBuilder.addTarget(previewSurface);
// Set up Surface for the MediaRecorder
Surface recorderSurface = mMediaRecorder.getSurface();
surfaces.add(recorderSurface);
mPreviewBuilder.addTarget(recorderSurface);
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull final CameraCaptureSession cameraCaptureSession) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPreviewSession = cameraCaptureSession;
updatePreview();
mIsRecordingVideo = true;
startTime = SystemClock.uptimeMillis();
mChronometer.setVisibility(View.VISIBLE);
customHandler.postDelayed(updateTimerThread, 0);
mRecordButton.setImageResource(R.drawable.ic_video_stop);
mMediaRecorder.start();
mCheckPoint.setEnabled(true);
}
});
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(RecordVideoActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
e.printStackTrace();
}
}
private void closePreviewSession() {
if (mPreviewSession != null) {
mPreviewSession.close();
mPreviewSession = null;
}
}
#SuppressLint("ResourceType")
private void stopRecordingVideo() {
mIsRecordingVideo = false;
customHandler.removeCallbacks(updateTimerThread);
mRecordButton.setImageResource(R.drawable.ic_video);
if(mMediaRecorder!=null) {
try {
mMediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
}
mMediaRecorder.reset();
}
}
static class CompareSizesByArea implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
(long) rhs.getWidth() * rhs.getHeight());
}
}
#Override
protected void onDestroy() {
customHandler.removeCallbacks(updateTimerThread);
}
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
I have implemented following coding in my app.i used camera 2 api for video recording.i feel that video streaming is stretched. mainly when i switch camera into front one.pls help me to resolve this problem
Change aspect ratio values in AutoFitTextureView class or use Textureview instead of AutoFitTextureview.

Facebook login page doesn't show my score only happens for admin

after I log onto Facebook and everything, it works fine but when I try to show my friend's score it doesn't brings up the score the score would be zero all the time, except for the admin account which is mine, it shows up my actual score, and here are the scripts for the Facebook and also for the score manager of mine, any suggestions?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static int score;
Text scoretext;
void Start ()
{
scoretext = GetComponent<Text> () ;
//score = 0;
score = PlayerPrefs.GetInt("CurrentPlayerScore");
}
void Update ()
{
if (score <0)
score = 0;
scoretext.text = "" + score;
}
public static void AddPoints (int pointsToAdd)
{
score +=pointsToAdd;
PlayerPrefs.SetInt ("CurrentPlayerScore", score);
}
public static void Rest()
{
score = 0;
PlayerPrefs.SetInt("CurrentPlayerScore", score);
}
}
and this is Facebook's one
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class FBholder : MonoBehaviour
{
public GameObject UIFBIsLoggedIn;
public GameObject UIFBIsNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFUserName;
private List<object> scoresList = null;
public GameObject ScoreEntryPanel;
public GameObject ScoreScrollList;
public static int score;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init (SetInit, OnHideUnity);
}
void Start()
{
score = PlayerPrefs.GetInt("CurrentPlayerScore");
}
private void SetInit()
{
Debug.Log ("FB Init done.");
if(FB.IsLoggedIn)
{
DealWithFBMenus(true);
Debug.Log ("FB Logged In");
}
else
{
DealWithFBMenus(false);
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale =0;
}
else
{
Time.timeScale =1;
}
}
public void FBlogin()
{
FB.Login ("email,publish_actions", AuthCallback);
}
void AuthCallback (FBResult result)
{
if (FB.IsLoggedIn)
{
Debug.Log ("FB Login worked!");
DealWithFBMenus(true);
}
else
{
Debug.Log ("Fb Login fail");
DealWithFBMenus(false);
}
}
void DealWithFBMenus (bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive(true);
UIFBIsNotLoggedIn.SetActive(false);
FB.API (Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
FB.API ("/me?field=id,first_name",Facebook.HttpMethod.GET, DealWiththeUserName);
}
else
{
UIFBIsLoggedIn.SetActive(false);
UIFBIsNotLoggedIn.SetActive(true);
}
}
void DealWithProfilePicture(FBResult result)
{
if (result.Error != null)
{
Debug.Log ("Problem with getting profile picture");
FB.API (Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
return;
}
Image UserAvatar = UIFBAvatar.GetComponent<Image>();
UserAvatar.sprite = Sprite.Create (result.Texture, new Rect (0,0,128, 128), new Vector2 (0,0));
}
void DealWiththeUserName (FBResult result)
{
if (result.Error != null)
{
Debug.Log ("Problem with getting user name");
FB.API ("/me?field=id,first_name",Facebook.HttpMethod.GET, DealWiththeUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
Text UserMsg = UIFUserName.GetComponent<Text>();
UserMsg.text = "Hello, " + profile["first_name"];
}
public void ShareWithFriends()
{
FB.Feed (
linkCaption: "I'm Playing this awesome game check it out!",
picture: "http://stormyx.com/MyGameIcon.png",
linkName: "Come join me in this game now!",
link: "http://app.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest")
);
}
public void InviteFriends()
{
FB.AppRequest
(
message: "This game is Fantastic!, join me now!",
title: "Invite your friends to join you"
);
}
public void FriendsScore()
{
FB.API ("/app/scores?fields=score,user.limit(30)", Facebook.HttpMethod.GET,ScoresCallback);
}
private void ScoresCallback (FBResult result)
{
Debug.Log ("Scores callback: " + result.Text);
scoresList = Util.DeserializeScores (result.Text);
foreach(Transform child in ScoreScrollList.transform)
{
GameObject.Destroy(child.gameObject);
}
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry ["user"];
GameObject ScorePanel;
ScorePanel = Instantiate (ScoreEntryPanel) as GameObject;
ScorePanel.transform.parent = ScoreScrollList.transform;
Transform ThisScoreName = ScorePanel.transform.Find ("FriendName");
Transform ThisScoreScore = ScorePanel.transform.Find ("FriendScore");
Text ScoreName = ThisScoreName.GetComponent<Text>();
Text ScoreScore = ThisScoreScore.GetComponent<Text>();
ScoreName.text = user["name"].ToString();
ScoreScore.text = entry["score"].ToString();
ScoreName.text = user["name"].ToString();
ScoreScore.text = entry["score"].ToString();
Transform TheUserAvatar = ScorePanel.transform.Find ("FriendAvatar");
Image UserAvatar = TheUserAvatar.GetComponent<Image>();
FB.API (Util.GetPictureURL(user["id"].ToString(), 128,128), Facebook.HttpMethod.GET,delegate(FBResult pictureResult)
{
if(pictureResult.Error != null)
{
Debug.Log (pictureResult.Error);
}
else
{
UserAvatar.sprite = Sprite.Create (pictureResult.Texture, new Rect (0,0,128, 128), new Vector2 (0,0));
}
});
}
}
public void MyScore()
{
var scoreData = new Dictionary<string,string>();
scoreData ["score"] = (score).ToString();
FB.API ("/me/scores", Facebook.HttpMethod.POST, delegate(FBResult result)
{
Debug.Log ("Score submit result: " + result.Text);
}, scoreData);
}
public void StartGame ()
{
PlayerPrefs.SetInt("CurrentPlayerScore",0);
Application.LoadLevel (1);
}
public void Quit ()
{
Application.Quit ();
}
}

I am getting error while importing Policymanager?

I am writing code for my own media-controller for VideoView.
and my code is as follows
public class FMediaController extends FrameLayout {
private MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private WindowManager mWindowManager;
private Window mWindow;
private View mDecor;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
private View.OnClickListener mNextListener, mPrevListener;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mFfwdButton;
private ImageButton mRewButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
public FMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = this;
mContext = context;
mUseFastForward = true;
mFromXml = true;
}
#Override
public void onFinishInflate() {
if (mRoot != null)
initControllerView(mRoot);
}
public FMediaController(Context context, boolean useFastForward) {
super(context);
mContext = context;
mUseFastForward = useFastForward;
initFloatingWindow();
}
public FMediaController(Context context) {
super(context);
mContext = context;
mUseFastForward = true;
initFloatingWindow();
}
private void initFloatingWindow() {
mWindowManager = (WindowManager)mContext.getSystemService("window");
mWindow = PolicyManager.makeNewWindow(mContext);
mWindow.setWindowManager(mWindowManager, null, null);
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mDecor = mWindow.getDecorView();
mDecor.setOnTouchListener(mTouchListener);
mWindow.setContentView(this);
mWindow.setBackgroundDrawableResource(android.R.color.transparent);
// While the media controller is up, the volume control keys should
// affect the media stream type
mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
requestFocus();
}
private OnTouchListener mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mShowing) {
hide();
}
}
return false;
}
};
public void setMediaPlayer(MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
/**
* Set the view that acts as the anchor for the control view.
* This can for example be a VideoView, or your Activity's main view.
* #param view The view to which to anchor the controller when it is visible.
*/
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
/**
* Create the view that holds the widgets that control playback.
* Derived classes can override this to create their own.
* #return The controller view.
* #hide This doesn't work as advertised
*/
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View v) {
mPauseButton = (ImageButton) v.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
if (mFfwdButton != null) {
mFfwdButton.setOnClickListener(mFfwdListener);
if (!mFromXml) {
mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
mRewButton = (ImageButton) v.findViewById(R.id.rew);
if (mRewButton != null) {
mRewButton.setOnClickListener(mRewListener);
if (!mFromXml) {
mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
// By default these are hidden. They will be enabled when setPrevNextListeners() is called
mNextButton = (ImageButton) v.findViewById(R.id.next);
if (mNextButton != null && !mFromXml && !mListenersSet) {
mNextButton.setVisibility(View.GONE);
}
mPrevButton = (ImageButton) v.findViewById(R.id.prev);
if (mPrevButton != null && !mFromXml && !mListenersSet) {
mPrevButton.setVisibility(View.GONE);
}
mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = (TextView) v.findViewById(R.id.time);
mCurrentTime = (TextView) v.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
installPrevNextListeners();
}
/**
* Show the controller on screen. It will go away
* automatically after 3 seconds of inactivity.
*/
public void show() {
show(sDefaultTimeout);
}
/**
* Show the controller on screen. It will go away
* automatically after 'timeout' milliseconds of inactivity.
* #param timeout The timeout in milliseconds. Use 0 to show
* the controller until hide() is called.
*/
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
int [] anchorpos = new int[2];
mAnchor.getLocationOnScreen(anchorpos);
WindowManager.LayoutParams p = new WindowManager.LayoutParams();
p.gravity = Gravity.TOP;
p.width = mAnchor.getWidth();
p.height = LayoutParams.WRAP_CONTENT;
p.x = 0;
p.y = anchorpos[1] + mAnchor.getHeight() - p.height;
p.format = PixelFormat.TRANSLUCENT;
p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
p.token = null;
p.windowAnimations = 0; // android.R.style.DropDownAnimationDown;
mWindowManager.addView(mDecor, p);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
}
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
mHandler.removeMessages(SHOW_PROGRESS);
mWindowManager.removeView(mDecor);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
int pos;
switch (msg.what) {
case FADE_OUT:
hide();
break;
case SHOW_PROGRESS:
pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
}
break;
}
}
};
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent ev) {
show(sDefaultTimeout);
return false;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (event.getRepeatCount() == 0 && event.isLongPress() && (
keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ||
keyCode == KeyEvent.KEYCODE_SPACE)) {
doPauseResume();
show(sDefaultTimeout);
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
updatePausePlay();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// don't show the controls for volume adjustment
return super.dispatchKeyEvent(event);
} else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
hide();
return true;
} else {
show(sDefaultTimeout);
}
return super.dispatchKeyEvent(event);
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void updatePausePlay() {
if (mRoot == null)
return;
ImageButton button = (ImageButton) mRoot.findViewById(R.id.pause);
if (button == null)
return;
if (mPlayer.isPlaying()) {
button.setImageResource(android.R.drawable.ic_media_pause);
} else {
button.setImageResource(android.R.drawable.ic_media_play);
}
}
private void doPauseResume() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
long duration;
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
duration = mPlayer.getDuration();
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromtouch) {
if (fromtouch) {
mDragging = true;
duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
}
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
}
};
#Override
public void setEnabled(boolean enabled) {
if (mPauseButton != null) {
mPauseButton.setEnabled(enabled);
}
if (mFfwdButton != null) {
mFfwdButton.setEnabled(enabled);
}
if (mRewButton != null) {
mRewButton.setEnabled(enabled);
}
if (mNextButton != null) {
mNextButton.setEnabled(enabled && mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setEnabled(enabled && mPrevListener != null);
}
if (mProgress != null) {
mProgress.setEnabled(enabled);
}
super.setEnabled(enabled);
}
private View.OnClickListener mRewListener = new View.OnClickListener() {
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos -= 5000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFfwdListener = new View.OnClickListener() {
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos += 15000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private void installPrevNextListeners() {
if (mNextButton != null) {
mNextButton.setOnClickListener(mNextListener);
mNextButton.setEnabled(mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setEnabled(mPrevListener != null);
}
}
public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
mNextListener = next;
mPrevListener = prev;
mListenersSet = true;
if (mRoot != null) {
installPrevNextListeners();
if (mNextButton != null && !mFromXml) {
mNextButton.setVisibility(View.VISIBLE);
}
if (mPrevButton != null && !mFromXml) {
mPrevButton.setVisibility(View.VISIBLE);
}
}
}
public interface MediaPlayerControl {
void start();
void pause();
int getDuration();
int getCurrentPosition();
void seekTo(int pos);
boolean isPlaying();
int getBufferPercentage();
};
}
and I am getting error at "Policy manager" at initfloatwindow method and I have imported import com.android.internal.policy.PolicyManager
private void initFloatingWindow() {
mWindowManager = (WindowManager)mContext.getSystemService("window");
mWindow = PolicyManager.makeNewWindow(mContext);//I got error here
mWindow.setWindowManager(mWindowManager, null, null);
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mDecor = mWindow.getDecorView();
mDecor.setOnTouchListener(mTouchListener);
mWindow.setContentView(this);
mWindow.setBackgroundDrawableResource(android.R.color.transparent);
// While the media controller is up, the volume control keys should
// affect the media stream type
mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
requestFocus();
}
Please anyone can help me please.Thanks in advance
PolicyManager is an internal class, not in puplic API so you cannot use it.