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) {
}
});
}
}
}
Related
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.
I have a media player service that plays a music in background, and this service is called from an activity. Now when i ex. exit from that activity, and get back to it again, i want to see what is the status, what song is played etc.
Here is the code from my service:
public class MediaPlayerService extends Service implements
OnCompletionListener, OnClickListener {
MediaPlayer mediaPlayer;
String url;
int mediaPos, mediaMax, position;
boolean isShufle;
WeakReference<SeekBar> seekbar;
WeakReference<TextView> reciter, songTitle, songPos;
private WeakReference<ImageView> play, forward, backward;
ArrayList<Songs> songs;
Handler handler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// mediaPlayer = MediaPlayer.create(this,url);// raw/s.mp3
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
private void play(final int position) throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException {
/*
* dialog = ProgressDialog.show(AlbumDetails.this, "",
* getString(com.darkovski.quran.R.string.buffering), true);
* dialog.setCancelable(true); dialog.show();
*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(songs.get(position).getLink());
// prepare track
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
play.get().setImageResource(R.drawable.pause);
// play.setImageResource(R.drawable.pause);
// this is new
mediaPos = mp.getCurrentPosition();
mediaMax = mp.getDuration();
reciter.get().setText(songs.get(position).getRecitorName());
songTitle.get().setText(songs.get(position).getTitle());
songPos.get().setText((position + 1) + " of 114");
seekbar.get().setMax(mediaMax);
seekbar.get().setProgress(mediaPos);
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
mp.start();
// dialog.dismiss();
}
});
// when truck finishes
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// if(shuffle)
try {
if (isShufle) {
play(new Random().nextInt(songs.size()));
} else {
if (position == songs.size())
play(0);
else
play(position + 1);
}
AlbumDetails.position += 1;
} 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();
}
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
url = intent.getStringExtra("url");
handler = new Handler();
position = intent.getIntExtra("position", -1);
forward = new WeakReference<ImageView>(AlbumDetails.forward);
backward = new WeakReference<ImageView>(AlbumDetails.backward);
play = new WeakReference<ImageView>(AlbumDetails.play);
play.get().setOnClickListener(this);
forward.get().setOnClickListener(this);
backward.get().setOnClickListener(this);
seekbar = new WeakReference<SeekBar>(AlbumDetails.seekbar);
reciter = new WeakReference<TextView>(AlbumDetails.reciter);
songTitle = new WeakReference<TextView>(AlbumDetails.songTitle);
songPos = new WeakReference<TextView>(AlbumDetails.songPos);
songs = AlbumDetails.songs;
seekbar.get().setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(progress);
}
}
});
/*
* try { mediaPlayer.setDataSource(url); mediaPlayer.prepare();
* mediaPlayer.setOnCompletionListener(this); } 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(); } if (!mediaPlayer.isPlaying()) {
* mediaPlayer.start(); }
*/
try {
play(position);
} 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();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekbar.get().setMax(mediaMax_new);
seekbar.get().setProgress(mediaPos_new);
handler.postDelayed(this, 100);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.playeer_back:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (position - 1 < 0) {
play(songs.size());
position = songs.size();
} else
play(position - 1);
} catch (IllegalArgumentException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (SecurityException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case R.id.playeer_forward:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
play(position + 1);
position += 1;
} 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();
}
break;
case R.id.playeer_play:
if (mediaPlayer == null) {
try {
play(position);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
play.get().setImageResource(R.drawable.pause);
} else if (mediaPlayer != null) {
mediaPlayer.start();
play.get().setImageResource(R.drawable.play_play);
}
// playFunction();
break;
}
}
}
And my activity code - onClick:
case R.id.playeer_play:
playbackServiceIntent
.putExtra("url", songs.get(position).getLink());
playbackServiceIntent
.putExtra("position", position);
startService(playbackServiceIntent);
break;
There are different methods to realize it.
Using LocalBroadcastManager
Using an application to track the status of your service, i.e Song name, length, ...
Using SharedPreferences
IMHO, I think using a LocalBroadcastManager is more cleaner.
- Send a broadcast message to the service
- When the service receives the message, let it broadcast its status.
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 have used ASyncTask before and have not faced any problems. I don't understand why this code is not working. I have to access an ftp server to download a text file that i set to a TextView. The code within the ASyncTask works fine. I have checked it. For some reason I am getting a problem when I call the new thread 'new GetStory().execute'. Any help would be great.
package com.amazingstories;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayStory extends Activity {
String path;
TextView story;
FTPClient ftp = new FTPClient();
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
path = getIntent().getExtras().getString("path");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.displaystory);
story = (TextView) findViewById(R.id.tvStory);
story.setText(path);
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"temp.txt");
new GetStory().execute();
// try{
// new GetStory().execute();
// }catch(Exception e){
// Toast.makeText(getApplicationContext(), e.toString(),
// Toast.LENGTH_SHORT).show();
//
// }
}
public class GetStory extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
try {
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
if (!ftp.isConnected()) {
ftp.connect(".....");
Toast.makeText(getApplicationContext(),
"connected to server", Toast.LENGTH_SHORT).show();
ftp.login("....", ".....");
}
Toast.makeText(getApplicationContext(), "FTP Connected",
Toast.LENGTH_SHORT).show();
ftp.changeDirectoryUp();
ftp.download(path, file, new FTPDataTransferListener() {
//ProgressDialog dialog;
#Override
public void aborted() {
// TODO Auto-generated method stub
// dialog.dismiss();
story.setText("Transfer Aborted");
}
#Override
public void completed() {
// TODO Auto-generated method stub
//dialog.dismiss();
}
#Override
public void failed() {
// TODO Auto-generated method stub
//dialog.dismiss();
story.setText("Transfer Failed");
}
#Override
public void started() {
// TODO Auto-generated method stub
//dialog = ProgressDialog.show(DisplayStory.this, "",
// "Loading. Please wait...", true);
}
#Override
public void transferred(int arg0) {
// TODO Auto-generated method stub
}
});
// tv.setText(test.toString());
Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_SHORT).show();
} catch (FTPException e) {
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPDataTransferException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),
"Exception Caught " + e, Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (FTPAbortedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
ftp.logout();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FTPIllegalReplyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getFileData get = new getFileData();
try {
story.setText(get.getData(file));
Toast.makeText(getApplicationContext(), "Set TextView",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file.delete();
}
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Try",
Toast.LENGTH_SHORT).show();
You are not allowed to call Toast inside doInBackground.
doInBackground method runs in non-ui thread so you can not manipulate or sidplay Toast on UI.It must be done in onPreExecute or in onPostExceute.
The methods onPreExecute(), onPostExecute(), and onProgressUpdate() are the only methods during an AsyncTask execution that are called on the main (UI) thread, and therefore are the only places you can directly make calls to UI methods (like TextView.setText() and Toast.makeText()).
Your program is likely crashing because you cannot create a Toast from a thread where "a Looper has not been prepared", which is what happends when you do so from doInBackground(); this causes an exception and a crash.
I am trying to use two instances of mediaplayer. When the first instance is played the second instance is prepared in another thread.and when first instance completes the file the second instance is started.
Problem: the second instance plays only audio, video is not visible.
Observation:If i prepare the second instance with the same surface holder as that of the first and start after first instance is completed it works fine.
Here is the code
package com.THER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.THER.MessengerServiceActivities.IncomingHandler;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.VideoView;
import android.widget.ViewSwitcher;
public class MediaPlayerActivity extends Activity implements OnCompletionListener, Callback, OnPreparedListener {
private MediaPlayer mMediaPlayer1 = null;
private SurfaceView mPreview1;
private SurfaceHolder holder1;
private ViewSwitcher switcher;
Integer counter = 0;
Integer played_files = 1;
private MediaPlayer mMediaPlayer2 = null;
private SurfaceView mPreview2;
private SurfaceHolder holder2;
boolean mIsBound;
boolean finish_flag = false;
/** Messenger for communicating with service. */
Messenger mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent;
super.onCreate(savedInstanceState);
setContentView(R.layout.videoview);
doBindService();
intent = getIntent();
counter=intent.getIntExtra("counter",counter);
mPreview1 =(SurfaceView)findViewById(R.id.surfaceView1);
holder1 = mPreview1.getHolder();
holder1.addCallback(this);
holder1.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPreview2 =(SurfaceView)findViewById(R.id.surfaceView2);
holder2 = mPreview2.getHolder();
holder2.addCallback(this);
holder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer1 = new MediaPlayer();
mMediaPlayer1.setScreenOnWhilePlaying(true);
mMediaPlayer2 = new MediaPlayer();
mMediaPlayer2.setScreenOnWhilePlaying(true);
try {
mMediaPlayer1.setDataSource("/sdcard/1.mp4");
mMediaPlayer1.setDisplay(holder1);
} 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();
}
mMediaPlayer1.setOnCompletionListener(this);
mMediaPlayer1.setOnPreparedListener(this);
//mMediaPlayer2.setOnPreparedListener(this);
mMediaPlayer2.setOnCompletionListener(this);
}
private class MediaPlayerTask extends AsyncTask<MediaPlayer, Void, String> implements OnCompletionListener {
String file;
private SurfaceHolder holder;
#Override
protected String doInBackground(MediaPlayer... mp1) {
// TODO Auto-generated method stub
//mp1[0].reset();
if(counter%2 == 0)
{
file = "/sdcard/2.mp4";
holder = holder2;
}
else
{
file = "/sdcard/1.mp4";
holder = holder1;
}
try {
mp1[0].reset();
mp1[0].setDataSource(file);
mp1[0].setDisplay(holder);
mp1[0].prepare();
mp1[0].setOnCompletionListener(this);
//mp1[0].start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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();
}
return null;
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
public void onCompletion(MediaPlayer mp)
{
if(counter%2 == 0)
{
played_files++;
mMediaPlayer1.stop();
mMediaPlayer1.release();
mMediaPlayer2.start();
}
else
{
played_files++;
mMediaPlayer2.stop();
mMediaPlayer2.release();
mMediaPlayer1.start();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
if(counter%2 == 0)
{
mMediaPlayer2.prepare();
}
else
{
mMediaPlayer1.prepare();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
//if(counter == 1)
mp.start();
}
}
Please take a look at the following thread:
http://groups.google.com/group/android-developers/browse_thread/thread/7d08a124a2e48bb3?pli=1
It looks like using two SurfaceViews was not intended by the Android developers.