Media Controllers are not visible on the top of the surface view .I have tried almost all the options
Surface View should disappear every time an channel is clicked from the list.
Then the Flip animation for the background Images takes place.
Then the Surface should be visible.
The above three steps happen for every click.
Every time i have tried doing the below give things. Surface View would disappear the first time But appear while the flip animation is happening and the n Never disppears
Set Visibility(inivisible ,gone )- nothing works
Changing the size of the surface view
BringToFront paired with invalidate()
Finally i tried
mSurface .setZOrderOnTop(true);
mHolder.setPixelFormat(Transparent)
That Worked But now the Problem is My Media Controllers that were attached to FrameLayout are not getting displayedand the Reason is ofcourse
mSurface.setZOrderOnTop(true);
Can Any body please please please to power of infinity tell me what should i do to get the media controllers to show up or get the whole Scenario worked out .
I am quite new to media player and surface views.
Please Help
MainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initImageLoader(getApplicationContext());
setContentView(R.layout.user_main_screen);
ActionBar actionBar = getActionBar();
actionBar.show();
// // get action bar
// ActionBar actionBar = getActionBar();
//
// // Enabling Up / Back navigation
// actionBar.setDisplayHomeAsUpEnabled(true);
SetUpVariables();
getDataFromSignIn();
Categories categoriesList = new Categories(UserMainScreen.this);
try {
resultFromCategoriesAsyncTask= categoriesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Language LanguagesList = new Language(UserMainScreen.this);
try {
resultFromLanguagesAsyncTask= LanguagesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MainScreen mainScreen = new MainScreen(UserMainScreen.this);
try {
resultFromAsyncTask= mainScreen.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
getChannelInfo(resultFromAsyncTask);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* changed the Thread variable policy variable -lalita */
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
ParentLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
PreviewFrameImage = (ImageView)findViewById(R.id.previewScreenImageView);
PreviewFrameImage.setOnTouchListener(this);
Bitmap PreviewImage = BitmapFactory.decodeResource(getResources(), R.drawable.tvscreen_white);
PreviewFrameImage.setImageBitmap(Bitmap.createScaledBitmap( PreviewImage, 350 , 180 , true));
PreviewFrame = (FrameLayout)findViewById(R.id.videoSurfaceContainer);
mSurface = (SurfaceView) findViewById(R.id.surface_main);
mSurface .setZOrderOnTop(true);
// mSurface.setVisibility(View.GONE);
//PreviewFrame.removeView(mSurface);
mHolder = mSurface.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller = new VideoControllerView(this);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.setVisibility(View.INVISIBLE);
InitImgList();
Integer[] images = (Integer[])imgList.toArray(new Integer[imgList.size()]);
for( int i = 0; i <ChannelThumbnails.size() ; i++)
{
Log.e(TAG,"ResponseData----- lalita test ---- channel Image Path "+ChannelThumbnails.get(i));
}
com.ib.coverflow.FlowImageAdapter coverImageAdapter = new com.ib.coverflow.FlowImageAdapter(this,ChannelThumbnails.toArray( new String[ChannelThumbnails.size()]),180, 150);
//coverImageAdapter.createReflectedImages();
CoverFlow coverFlow = (CoverFlow) findViewById(R.id.coverflow);
coverFlow.setAdapter(coverImageAdapter);
//coverFlow.setSpacing(-20);
coverFlow.setSelection(30);
setupListeners(coverFlow);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.user_main_screen_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* On selecting action bar icons
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_refresh:
// refresh
return true;
case R.id.action_user:
// help action
return true;
case R.id.action_menu:
// check for updates action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void InitImgList() {
imgList.add(R.drawable.img01);
imgList.add(R.drawable.img02);
imgList.add(R.drawable.img03);
imgList.add(R.drawable.img04);
}
#SuppressWarnings("unchecked")
private void getChannelInfo(String ResultDataFroMsERVER) throws JSONException {
// TODO Auto-generated method stub
channelInfo = resultFromAsyncTask;
Log.e(TAG,"channel Information " +channelInfo );
/*
* Json object for parsing the data(Channel Info)
// */
try {
json = new JSONObject(channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ResponseData= json.getJSONArray("Response Data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0 ; i <ResponseData.length();i++)
{
jsonobjectresponsedata = ResponseData.getJSONObject(i);
ChannelID.add(jsonobjectresponsedata.getString("channel_id")) ;
ChannelType.add(jsonobjectresponsedata.getString("channel_type")) ;
VideoType.add(jsonobjectresponsedata.getString("video_type")) ;
ChannelName.add(jsonobjectresponsedata.getString("name")) ;
channelLink.add(jsonobjectresponsedata.getString("link")) ;
ChannelThumbnails.add( jsonobjectresponsedata.getString("img_path")) ;
}
}
private void getDataFromSignIn() {
// TODO Auto-generated method stub
Intent InfoFromSignScreen = getIntent();
UserName = InfoFromSignScreen.getCharSequenceExtra("UserName").toString();
AccessToken = InfoFromSignScreen.getCharSequenceExtra("AccessToken").toString();
Log.e (TAG, "LALITA TEST ***************** USERNAME AND aCCESS TOKEN " + UserName + " "+AccessToken);
}
private void SetUpVariables() {
// TODO Auto-generated method stub
tv = (TextView)findViewById(R.id.textView1);
}
private void FlipImageViewOnClick() {
// TODO Auto-generated method stub
ObjectAnimator animation = ObjectAnimator.ofFloat(PreviewFrameImage, "rotationY", 0.0f, 180f);
animation.setDuration(1500);
animation.setRepeatCount(0);
//animation.setRepeatCount(ObjectAnimator.RESTART);
animation.setInterpolator(new AccelerateInterpolator());
animation.start();
animation.addListener(new AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
//PreviewFrameImage.bringToFront();
// mSurface.invalidate();
Toast.makeText(getBaseContext(), "ANimation START ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ANimationREPEAT", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(0);
// mSurface.bringToFront();
// mSurface.setVisibility(View.VISIBLE);
Toast.makeText(getBaseContext(), "ANimation Endded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
}
/**
* Setup cover flow.
*
* #param mCoverFlow
* the m cover flow
* #param reflect
* the reflect
*/
/**
* Sets the up listeners.
*
* #param mCoverFlow
* the new up listeners
*/
private void setupListeners(final CoverFlow coverFlow) {
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
/*
* Hls Streams
*/
if(channelLink.get(position).endsWith("m3u8")) {
Log.e(TAG," ******* HLS*************** " +channelLink.get(position) );
if(mMediaPlayer!= null )
{
// mSurface .setZOrderOnTop(true);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
// mSurface.setVisibility(View.VISIBLE);
//PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
playHlsStreams(channelLink.get(position));
}
else
{
FlipImageViewOnClick();
//mSurface .setZOrderOnTop(false);
// mSurface.setVisibility(View.VISIBLE);
// PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
//mHolder.setFormat(PixelFormat.OPAQUE);
playHlsStreams(channelLink.get(position));
}
}
/*
* Octoshape Streams
*/
else if (channelLink.get(position).startsWith("octoshape"))
{
Log.e(TAG," octoshape " +channelLink.get(position) );
if(mMediaPlayer != null)
{
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
mHolder.setFormat(PixelFormat.OPAQUE);
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
FlipImageViewOnClick();
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
Toast.makeText(getBaseContext(), "Youtube Work In Progress and RTMP PLAYER NOT AVAILABLE ", Toast.LENGTH_LONG).show();
}
}
});
}
private void playHlsStreams(String OCTOLINK1) {
// TODO Auto-generated method stub
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
try {
mMediaPlayer.setDataSource(this, Uri.parse(OCTOLINK1));
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.start();
}
public void initOctoshapeSystem(final String OCTOLINK1)
{
os = OctoshapeSystemCreator.create(this, problemListener,
new OctoshapePortListener() {
#Override
public void onPortBound(int port) {
setupStream(OCTOLINK1).requestPlay();
}
}, Locale.ENGLISH.getLanguage());
os.setProblemMessageLanguage(Locale.ENGLISH.getLanguage());
os.setProblemListener(problemListener);
os.addPlayerNameAndVersion(MediaPlayerConstants.NATIVE_PLAYER, MediaPlayerConstants.NATIVE_PLAYER,
"" + Build.VERSION.SDK_INT);
os.open();
}
public StreamPlayer setupStream(final String stream) {
Log.d(LOGTAG, "Setting up stream: " + stream);
StreamPlayer sp = os.createStreamPlayer(stream);
sp.setProblemListener(new ProblemListener() {
#Override
public void gotProblem(Problem p) {
StreamStatus="No Stream/Internet Problem";
Log.i("Stream Status ", "Not Ok");
active="yellow";
Log.e(LOGTAG, stream+": "+p.getMessage() + " " + p.toString());
}
});
sp.setListener(new StreamPlayerListener() {
private String playerId;
#Override
public void gotUrl(String url, long seekOffset,
boolean playAfterBuffer) {
Log.i(LOGTAG, "gotUrl");
if (playAfterBuffer)
urlQueue.add(Uri.parse(url));
else
playStream(Uri.parse(url), playerId);
}
#Override
public void gotNewOnDemandStreamDuration(long duration) {
}
#Override
public void resolvedNativeSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNativeSeek");
this.playerId = playerId;
}
#Override
public void resolvedNoSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNoSeek");
this.playerId = playerId;
}
#Override
/**
* Called when stream support OsaSeek / DVR
*/
public void resolvedOsaSeek(boolean isLive, long duration,
String playerId) {
Log.i(LOGTAG, "resolvedOsaSeek");
this.playerId = playerId;
}
});
//sp.initialize(false);
return sp;
}
protected void playStream(Uri mediaUrl, final String playerId) {
Log.d(LOGTAG, playerId + " now plays: " + mediaUrl);
try {
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
mMediaPlayer.setDataSource(this, mediaUrl);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (!urlQueue.isEmpty())
playStream(urlQueue.removeFirst(), playerId);
}
});
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
error("MediaPlayer Error: " + what + ":" + extra);
return true;
}
});
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
Log.e(LOGTAG, "Error preparing MediaPlayer", e);
error("Error preparing MediaPlayer: " + e.getMessage());
}
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
FrameLayout.LayoutParams vLayout = (FrameLayout.LayoutParams) mSurface
.getLayoutParams();
mSurface.setLayoutParams(vLayout);
// dialog.dismiss();
StreamStatus="Stream Ok";
Log.i("Stream Stattus", "Stream Ok");
active="true";
long startTime = System.currentTimeMillis();
System.out.println("dddddddddddddddddddddddddddddddddddddddddddddd"+startTime);
Timer timer = new Timer();
timer.schedule(new SayHello(), 50000, 60000);
}
#Override
public void onBackPressed() {
// do nothing.
}
public void shutdown(){
if (mMediaPlayer != null)
mMediaPlayer.release();
if (os != null) {
os.close(new Runnable() {
#Override
public void run() {
UserMainScreen.this.finish();
}
});
}
}
#Override
protected void onStop()
{
super.onStop();
Log.d(LOGTAG, "MY onStop is called");
shutdown();
}
ProblemListener problemListener = new ProblemListener() {
#Override
public void gotProblem(Problem p) {
Log.e(LOGTAG, p.getMessage() + "\n" + p.toString());
error(p.getMessage());
}
};
protected void error(final String error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// dialog.show();
Log.i(LOGTAG, "problem dialog block");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
class SayHello extends TimerTask {
public void run() {
System.out.println("Catche clear method scheduled");
clearCache();
}
}
void clearCache()
{
Log.d(LOGTAG, "clearCache() clled");
if (mClearCacheObserver == null)
{
mClearCacheObserver=new CachePackageDataObserver();
}
PackageManager mPM=getPackageManager();
#SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };
Long localLong=Long.valueOf(CACHE_APP);
try
{
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);
try
{
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
catch (NoSuchMethodException e1)
{
e1.printStackTrace();
}
}
private class CachePackageDataObserver extends IPackageDataObserver.Stub
{
public void onRemoveCompleted(String packageName, boolean succeeded)
{
}
}
#Override
public void surfaceCreated(SurfaceHolder mHolder) {
// TODO Auto-generated method stub
Log.e(TAG,"**************Surface created**************LOLZ ") ;
mMediaPlayer.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface CHANGED **************LOLZ ") ;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface destroyed **************LOLZ " );
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.e(TAG, "GET CURRENT POSITION " +mMediaPlayer.getCurrentPosition());
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
mMediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
public void toggleFullScreen() {
controller.hide();
mMediaPlayer.stop();
// intent = new Intent(UserMainScreen.this,
// MiniAndroidPlayer.class);
intent.putExtra("OCTO", OCTOLINK1);
startActivity(intent);
}
// End VideoMediaController.MediaPlayerControl
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(PreviewFrame == v )
{
controller.show();
//mSurface.invalidate();
Log.e(TAG, " Preview frame controller Show" +controller.isShown());
}
if( mSurface == v )
{
controller.show(); // do things
// mSurface.invalidate();
Log.e(TAG, " mSurface controller Show" +controller.isShown());
}
if (PreviewFrameImage == v)
{
controller.show(); // do things
Log.e(TAG, " PreviewFrameImage controller Show" +controller.isShown());
}
if ( youTubeView == v) {
controller.show(); // do things
//mSurface.invalidate();
Log.e(TAG, " youtubeView controller Show" +controller.isShown());
//
// controller.setVisibility(View.VISIBLE);
}
return false;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
// TODO Auto-generated method stub
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
// player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
//
// Hiding player controls
player.setPlayerStyle(PlayerStyle.MINIMAL);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
// done now getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
/*
* Uncomment again
*/
// private YouTubePlayer.Provider getYouTubePlayerProvider()
// {
// return (YouTubePlayerView) findViewById(R.id.youtube_view);
// }
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(-90);
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCache(new LimitedAgeDiscCache(cacheDir, 60))
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.defaultDisplayImageOptions(options)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
return false;
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ImageView
android:id="#+id/previewScreenImageView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginBottom="190dip"
android:layout_marginTop="20dp" />
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="205dp"
android:layout_marginLeft="270dp"
android:layout_marginRight="269dp"
android:layout_marginTop="30dp"
android:text="framelayout"
>
<!-- <com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent" /> -->
<SurfaceView
android:id="#+id/surface_main"
android:layout_width="484dp"
android:layout_height="235dp"
/>
</FrameLayout>
<com.ib.coverflow.CoverFlow
xmlns:coverflow ="http://schemas.android.com/apk/res/com.ib.qezyplay"
android:id ="#+id/coverflow"
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="20dp">"
</com.ib.coverflow.CoverFlow>
</RelativeLayout>
service code :
public class AlarmListeningService extends Service{
public static final String sHost = "*.*.*.*";
public static final int sPort = 5566;
Thread thrSocket;
#SuppressWarnings("deprecation")
public void onStartCommand(Intent intent, int startId) {
super.onStartCommand(intent, startId, startId);
thrSocket = new thrSocket();
thrSocket.start();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
class thrSocket extends Thread {
Socket mSocket;
public void run() {
InitSocket();
new Thread(){
public void run() {
try {
String msg = "";
while (true) {
int count = 0;
while (count == 0) {
count=ips.available();
}
byte[] serverdata = new byte[count];
ips.read(serverdata);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
private void InitSocket(){
try {
mSocket = new Socket(sHost,sPort);
OutputStream out=mSocket.getOutputStream();
byte[] b_client = "client".getBytes(Charset.forName("UTF-8"));
out.write(b_client);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent startAL = new Intent();
startAL.setClass(MainActivity.this, AlarmListeningService.class);
startService(startAL);
}
My question is will the socket in service close when I destroy the activity
(Observation at socket server)?
And the socket will re-connection in seconds to tens of seconds (Observation at socket server too)
How could I let the socket not close when I destroy the activity?
I implemented signin with google with no problems. I am using a fragment in place of an activity.
Testing the code on samsung galaxies it happens that signin system goes idle and do not call onConnected method.
This happens just the first time, when the terms and conditions shows.
Any advice?
Here is my code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initGoogle()
}
private void initGoogle() {
mPlusClient = new PlusClient.Builder(getActivity() , this , this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
}
public void connectWithPlus() {
launchProgressScreen();
if(mPlusClient != null && !mPlusClient.isConnected()){
mPlusClient.connect();
}else{
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR) {
mConnectionResult = null;
connectWithPlus();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (result!= null && result.hasResolution()) {
try {
result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
connectWithPlus();
}
mConnectionResult = result;
}else{
onTaskResult(ProgressAlert.TASK_CANCEL_GOOGLE_LOGIN, null);
}
}
#Override
public void onConnected(Bundle connectionHint) {
AsyncTask<Object, Void, String> task = new AsyncTask<Object, Void, String>() {
#Override
protected String doInBackground(Object... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(getActivity(), mPlusClient.getAccountName(),
"oauth2:" + Scopes.PLUS_LOGIN );
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token){
getAuthDelegate().setToken(token, SocialAccount.google);
getAuthDelegate().loginUsingGoogle(token, new HashMap<String, String>());
}
};
task.execute();
}
#Override
public void onDisconnected() {
Log.w("Google Login", "called disconnected");
}
#Override
public void onClick(View v) {
connectWithPlus();
}
I faced same problem and I fixed it by overriding onResume method in Fragment.
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mGoogleApiClient.connect();
}
I am still not sure if its valid solution or not.
Thanks,
Rahul
You should process this catch block:
catch (UserRecoverableAuthException userRecoverableException) {
startActivity(userRecoverableException.getIntent());
}
First I created a class which is called GetMusics.java so i want to path music name to MusicPlater.java class but onActivityResult method doesn't work.I don't know where I am making mistake.
This is GetMusic.java class
public class GetMusics extends ListActivity{
private final String SD_PATH = Environment.getExternalStorageDirectory().getPath();
List<String> songs = new ArrayList<String>();
MediaPlayer mp = new MediaPlayer();
class Mp3Filter implements FilenameFilter{
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return filename.endsWith(".mp3");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.music_layout);
updateMusicList();
}
private void updateMusicList(){
File file = new File(SD_PATH);
if(file.listFiles(new Mp3Filter()).length>0){
for(File f : file.listFiles(new Mp3Filter()) ){
songs.add(f.getName());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
songs);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent i = new Intent(GetMusics.this,MusicPlayer.class);
i.putExtra("song_name", songs.get(position));
setResult(100,i);
finish();
}
}
and this is MusicPlayer.java class
public class MusicPlayer extends Activity {
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.music_player);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==100){
String song_name = data.getStringExtra("song_name");
mp.reset();
try {
mp.setDataSource(Environment.getExternalStorageDirectory()
.getPath() + "/" + song_name);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do I call the SensorManager from inside -
protected String doInBackground(String... params) {
.....
}
I have to log the acclerometer data on to a file. This application runs in the background. Hence I am using AsyncTask to implement it. I need to start and stop the logging by pressing the button (onClick). Any pointers would be helpful!!
This is the update... The file written is empty...How do I start the logging?
public class AsyncTaskActivity extends Activity implements SensorEventListener{
Button btn;
File root = Environment.getExternalStorageDirectory();
StringBuilder builder = new StringBuilder();
File gpxfile = new File(root, "TestFile.txt");
String fileText = "Data";
FileWriter gpxwriter;
BufferedWriter out;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LongOperation(new AsyncTaskActivity()).execute("");
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
private AsyncTaskActivity mActivity;
public LongOperation (AsyncTaskActivity activity) {
mActivity = activity;
}
#Override
protected String doInBackground(String... params) {
try {
gpxwriter = new FileWriter(gpxfile);
out = new BufferedWriter(gpxwriter);
if (root.canWrite()){
SensorManager manager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(!manager.registerListener((SensorEventListener) this, accelerometer, SensorManager.SENSOR_DELAY_GAME)){
System.out.println("Could not start!!!!!!!!!");
}
out.write("Start");
out.newLine();
out.close();
}
} catch (IOException e) {
Log.e("doIn","Could not write file " + e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("File written successfully!!!");
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
builder.setLength(0);
builder.append(event.values[0]+","+event.values[1]+","+event.values[2]);
try {
out.append(builder.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Pass the Activity Instance to the constructor of the AsyncTask and then access the Sensor Manager
class MyTask extends AsyncTask<URL, Integer, List> {
private MainActivity mActivity;
public MyTask(MainActivity activity) {
mActivity = activity;
}
protected List doInBackground(URL... url) {
SensorManager mSensorManager = (SensorManager)
mActivity.getSystemService(SENSOR_SERVICE)
....
return ..;
}
}