I tried to write the music player code in android.I want to show the current title of the song,artist and album image.
The Activity is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.PlayMusicService.LocalBinder;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GetMusic extends Activity implements OnGestureListener {
static Handler seekhandler=new Handler();
boolean isServiceConnected=false;
PlayMusicService playServ;
static TextView tv1,tv2,tv3;
Button previous,next;static ImageView img;static GestureDetector gDetector;
int pausePressed=1;static SeekBar sb;
int currentIndex=0;Cursor cursor;GenericSongClass GSC;
static MediaPlayer mediaPlayer;static int posofaudiotrack;
private ServiceConnection conn=new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isServiceConnected=false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder=(LocalBinder)service;
playServ=binder.getService();
isServiceConnected=true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_music);
gDetector= new GestureDetector(this);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
tv3=(TextView)findViewById(R.id.textView3);
getSongs();
img=(ImageView)findViewById(R.id.imageView1);
sb=(SeekBar)findViewById(R.id.seekBar1);
try{
Intent serv = new Intent(this,PlayMusicService.class);
bindService(serv, conn, Context.BIND_AUTO_CREATE);
System.out.println("in try calling service");
startService(serv);
}
catch(Exception e){
System.out.println("Exception is"+e);
}
System.out.println("after binding");
/*
try {
playSong(0);
}
catch(Exception e){
System.out.println("Exception is"+e);
}*/
//PlayMusic p=new PlayMusic();
// p.execute();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isServiceConnected) {
unbindService(conn);
isServiceConnected = false;
}
}
public static void mediaPlayerPause()
{
if(mediaPlayer!=null)
{
mediaPlayer.pause();
posofaudiotrack=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mediaPlayer!=null&&!mediaPlayer.isPlaying())
{
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
}
public class PlayMusic extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getSongs();
return null;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public static ArrayList<GenericSongClass> songs = null;
public void getSongs() {
Toast.makeText(getApplicationContext(), "in BindAllSongs()", Toast.LENGTH_SHORT).show();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.COMPOSER,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ALBUM
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = getBaseContext().getContentResolver().query(uri,
projection, selection, null, sortOrder);
/* int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String s=cursor.getString(column_index);*/
// Toast.makeText(getApplicationContext(), "path is"+s, Toast.LENGTH_SHORT).show();
// System.out.println("path is"+s);
if (null == cursor) {
Log.e("error","cursor is null");
// If the Cursor is empty, the provider found no matches
} else if (cursor.getCount() < 1) {
Log.i("info","cursor count<1");
} else {
songs = new ArrayList<GenericSongClass>(cursor.getCount());
cursor.moveToFirst();
int colIndex=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = cursor.getString(colIndex);
// Toast.makeText(getApplicationContext(), "PATH IS"+path, Toast.LENGTH_SHORT).show();
System.out.println("PATH IS"+path);
while (!cursor.isAfterLast()) {
GSC = new GenericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songComposer=cursor.getString(3);
GSC.title=cursor.getString(4);
GSC.album=cursor.getString(5);
songs.add(GSC);
cursor.moveToNext();
}
// Toast.makeText(getApplicationContext(), "songs first is"+songs.get(0).songTitle, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "songs length is"+songs.size(), Toast.LENGTH_SHORT).show();
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.e("I", "Media player has been loaded to memory !");
}
});
/*for(int i=0;i<songs.size();i++){
if(mediaPlayer.isPlaying())
mediaPlayer.reset();
String p=songs.get(i).songData;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "exception is"+ex, Toast.LENGTH_SHORT).show();
Log.i("ex is",ex.toString());
} finally {
if (cursor != null) {
cursor.close();
}}
}
protected void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
protected void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
private void playSong(int index) {
// TODO Auto-generated method stub
try{
mediaPlayer.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tv1.setText(songs.get(index).title);
tv2.setText(songs.get(index).album);
tv3.setText(songs.get(index).songArtist);
// tv3.append(songs.get(index).album);
mediaPlayer.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mediaPlayer.start();
sb.setMax(mediaPlayer.getDuration());
seekUpdation();
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
mediaPlayer.seekTo(seekBar.getProgress());
seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
playServ.getNextSong();
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
sb.setProgress(mediaPlayer.getCurrentPosition());
seekhandler.postDelayed(run, 1000);
}
public class GenericSongClass {
String songTitle = "";
String songArtist = "";
String songData = "";
String songComposer="";
String title="";
String album="";
String isChecked = "false";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_music, menu);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float velocityX,
float velocityY) {
pausePressed=1;//int x=playServ.getCurrentIndex();
// TODO Auto-generated method stub
if(start.getRawX() < finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "chanegd", Toast.LENGTH_SHORT).show();
if(playServ!=null){
/* if(x==0)
x=songs.size()-1;
else{
x=currentIndex-1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getPreviousSong();}
else
System.out.println("ms null");
}
else if(start.getRawX()>finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "changed on other", Toast.LENGTH_SHORT).show();
Log.d("onFLing","in onFling");
if(playServ!=null){
/*
if(x == songs.size()-1){
x=0;
}
else
{
x=x+1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getNextSong();
}
else
System.out.println("ms null");
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
System.out.println("PAUSEPRESSED"+pausePressed);
if(pausePressed==1){
pausePressed=0;
playServ.mediaPlayerPause();
}else if(pausePressed==0){
pausePressed=1;
//mediaPlayer.seekTo(posofaudiotrack);
playServ.mediaPlayerResume();
}
return true;
}
}
and the Service is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.GetMusic.GenericSongClass;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class PlayMusicService extends Service{
MediaPlayer mp;int currentIndex=0;
ArrayList<GenericSongClass> songs=GetMusic.songs;int pausePressed=1;
IBinder servbind=new LocalBinder();
public class LocalBinder extends Binder{
PlayMusicService getService()
{
return PlayMusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return servbind;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mp=new MediaPlayer();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
System.out.println("in onPrepared");
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
getNextSong();
}
});
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
System.out.println("in try");
playSong(0);
}
catch(Exception e){
System.out.println("in catch and exception is "+e.getMessage());
}
}
public void playSong(int index){
// TODO Auto-generated method stub
try{
System.out.println("in playsong");
mp.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
GetMusic.tv1.setText(songs.get(index).title);
GetMusic.tv2.setText(songs.get(index).album);
GetMusic.tv3.setText(songs.get(index).songArtist);
GetMusic.tv3.append(songs.get(index).album);
mp.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
GetMusic.img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mp.start();
GetMusic.sb.setMax(mp.getDuration());
seekUpdation();
GetMusic.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
mp.seekTo(seekBar.getProgress());
GetMusic.seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
GetMusic.sb.setProgress(mp.getCurrentPosition());
GetMusic.seekhandler.postDelayed(run, 1000);
}
public int getCurrentIndex(){
return currentIndex;
}
public void mediaPlayerPause()
{
if(mp!=null)
{
mp.pause();
//pos=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mp!=null&&!mp.isPlaying())
{
mp.seekTo(mp.getCurrentPosition());
mp.start();
}
}
public void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
public void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.start();
return 0;
}
#Override
public void onDestroy()
{
mp.release();
super.onDestroy();
}
}
The issue is it's playing good sometimes and sometimes it's stopping when we press back button or swiping other apps on home screen.I want to show the title track,image on UI.But with this code it's showing wrong images for some songs and for some it's even not showing the image even if the image exists.And after back screen pressed and so when we use other apps and get back to this It's showing simply TextView and normal android image.Is recreation of activity needed?Can we call Activity method from Service?How to solve the issues?Please help me.
You need background music service and communicate with Activity with message or bond activity to service, not call Activity method from service, that will cause cross process problem.
I actually opensource a Music Player with Background service, Lyric, from a business project I have wrote, you check this out:https://github.com/Wangchao0721/MusicPlayer
But I haven't got time to fill Readme for it, just check MediaPlayerActivity.java in activity package, you gonna know how to use this.
Hi I'm trying to clean other applications cache from my application, I'm able to clear other apps cache now till 4.1.2 version of android using the following code
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
public class CacheNukerActivity extends Activity {
private static final long ALL_YOUR_CACHE_ARE_BELONG_TO_US=1000000000L;
private CachePackageDataObserver mClearCacheObserver;
private TextView tv=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.status);
tv.setText("Clearing cache...");
clearCache();
}
private final void clearCache() {
if (mClearCacheObserver == null) {
mClearCacheObserver=new CachePackageDataObserver();
}
PackageManager mPM=getPackageManager();
#SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };
Long localLong=Long.valueOf(ALL_YOUR_CACHE_ARE_BELONG_TO_US);
try {
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);
try {
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private class CachePackageDataObserver extends
IPackageDataObserver.Stub {
public void onRemoveCompleted(String packageName, boolean succeeded) {
tv.post(new Runnable() {
public void run() {
tv.append(" cache cleared");
}
});
}
}
}
and the IPackageDataObserver code is
package android.content.pm;
oneway interface IPackageDataObserver {
void onRemoveCompleted(in String packageName, boolean succeeded);
}
But when I run the same application in 4.2 and above android version, cache is not clearing. Please someone help me.
I've found the solution guys, the working code snippet is as follows, just change the ALL_YOUR_CACHE_ARE_BELONG_TO_US long value from 1000000000L to Long.MAX_VALUE
public class CacheNukerActivity extends Activity {
private static final long ALL_YOUR_CACHE_ARE_BELONG_TO_US=Long.MAX_VALUE;
private CachePackageDataObserver mClearCacheObserver;
private TextView tv=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.status);
tv.setText("Clearing cache...");
clearCache();
}
private final void clearCache() {
if (mClearCacheObserver == null) {
mClearCacheObserver=new CachePackageDataObserver();
}
PackageManager mPM=getPackageManager();
#SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };
Long localLong=Long.valueOf(ALL_YOUR_CACHE_ARE_BELONG_TO_US);
try {
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);
try {
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private class CachePackageDataObserver extends
IPackageDataObserver.Stub {
public void onRemoveCompleted(String packageName, boolean succeeded) {
}
});
}
}
}
I am just not able to figure out the problem in my code
I want to login with FaceBook for my app
I have followed a tutorial from a youtube video.
in the code , I am able to login using facebook, but I am not able to implement the logout functionality.
i tried doing it. (the code for logging out is also there but still its not working)
the code is as follows:
after i click on login button:
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.fb_button:
try{
//to check if already logged in.
//my code never enters the following block.
if(fb.isSessionValid()){
Toast.makeText(getBaseContext(), "loging out", Toast.LENGTH_LONG).show();
try {
fb.logout(getBaseContext());
// update_fb_buttonimage() is a function to change the image of button
//if logged in: it shows logout
// else it shows login.
//but somehow its not working
update_fb_buttonimage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//following is working fine.
// but every time i click n the button, it enters this bolok of code.
//which is not what i want. this is tobe executed only if user is not logged in
//even if user is logged in , program enters this code only.
// instead of this th above "if" block should be executed.
else{
Toast.makeText(getBaseContext(), "logging in", Toast.LENGTH_LONG).show();
fb.authorize(LoginPage.this,new DialogListener(){
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
update_fb_buttonimage();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "You can't login to the facebook", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "unIdentified Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "onCancel", Toast.LENGTH_LONG).show();
}} );
} }catch(Exception e){
System.out.print(e.toString());
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
break;
}
Where is my error?
just replace the MainActivity.this with yours and updateButtonImage()
if(fb.isSessionValid())
{
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button close session
}
else
{
fb.authorize(MainActivity.this,new String[] {"publish_stream"}, new DialogListener(){
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(MainActivity.this, "on Facebook error", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(MainActivity.this, "on error", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
updateButtonImage();
}
#Override
public void onCancel()
{
}
});
//login in to facebook
}
i surfed net to find some code snippet or some help to integrate yahoo messenger in android application. i could not find some thing helpful.
Please Help me by providing some link, tutorial or code sample so that i could integrate the yahoo messenger.
Thanks
Finally got solution for yahoo messenger integration i used openymsg a library and using below link
http://edwin.baculsoft.com/2011/11/creating-a-simple-yahoo-messenger-auto-response-with-java-and-openymsg-library/
changed my code in activity as below worked like a charm :)
public class SimpleYahoo extends Activity implements SessionListener{
/** Called when the activity is first created. */
private Logger logger = Logger.getAnonymousLogger();
private Session session = new Session();
Button sendButton;
boolean isLoginsuccess;
ListView resultTextView;
EditText editText;
Handler handler;
ArrayList<String> replymessage;
String reply;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replymessage=new ArrayList<String>();
try {
session.login("yahooid", "password");
} catch (AccountLockedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LoginRefusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FailedLoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.addSessionListener(this);
sendButton=(Button) findViewById(R.id.button);
resultTextView=(ListView) findViewById(R.id.result);
editText=(EditText) findViewById(R.id.input);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLogin();
}
});
handler=new Handler()
{
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==0)
{
replymessage.add(reply);
setListAdapter();
}
}
};
}
private void doLogin() {
try {
// insert your yahoo id
// as for this example, im using my yahoo ID "dombaganas"
session.sendMessage("targetyahooid", editText.getText().toString());
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
#Override
public void dispatch(FireEvent fe) {
// TODO Auto-generated method stub
ServiceType type = fe.getType();
SessionEvent sessionEvent = fe.getEvent();
if (type == ServiceType.MESSAGE) {
try {
// log request message
reply=sessionEvent.getMessage();
Log.i("message","message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage() );
// give an automatic response
// session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
// session.
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
}
public void setListAdapter()
{
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.multi_line_list_item,replymessage);
resultTextView.setAdapter(arrayAdapter);
resultTextView.setSelection(replymessage.size()-1);
}
}
I'm using media player. I want to show progress bar while connection URL and media player get prepare, but I can't show it.
public class MainActivity extends Activity implements OnClickListener, Runnable{
MediaPlayer mPlayer;
ProgressBar pBar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Continue();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void Connect()
{
try {
Toast.makeText(getApplicationContext(),"Yayın Açılana Kadar Lütfen Bekleyiniz" , Toast.LENGTH_SHORT).show();
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mPlayer.start();
pBar.setVisibility(ProgressBar.VISIBLE);
pBar.setProgress(0);
pBar.setMax(mPlayer.getDuration());
new Thread(this).start();
if(mPlayer!=null)pBar.setVisibility(ProgressBar.GONE);
}
public void Continue()
{
mPlayer = new MediaPlayer();
String str = "http:MyURL";
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(str);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
Connect();
}
public void run() {
// TODO Auto-generated method stub
int currentPosition =0;
int total = mPlayer.getDuration();
while(mPlayer!=null && currentPosition<total){
try{
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
}catch(InterruptedException e){
return;
}catch(Exception e){
return;
}
pBar.setProgress(currentPosition);
}
}
}
You are calling pBar.setVisibility(ProgressBar.GONE); right after starting the thread..it will show and then disappear immediately..
Move it in the run method after the processing is done.