I\'m trying to check if com.android.music is running and I\'m getting the following error on this line this.getSystemService(Context.ACTIVITY_SERVICE);
getSystemService
is a method of the class Context
, so you'll need to run it on a context.
The original code you copied it from was probably meant to be run from an Activity
-derived class. You need to pass a Context
argument into your method if it's not inside an Activity.
Both the answer are correct but no one point out the right solution to your problem.
You should use broadcast receiver to get current playing song.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
Log.v("tag ", action + " / " + cmd);
String artist = intent.getStringExtra("artist");
String album = intent.getStringExtra("album");
String track = intent.getStringExtra("track");
Log.v("tag", artist + ":" + album + ":" + track);
Toast.makeText(CurrentMusicTrackInfoActivity.this, track, Toast.LENGTH_SHORT).show();
}
};
And add it onCreate
IntentFilter iF = new IntentFilter();
iF.addAction("com.android.music.metachanged");
iF.addAction("com.htc.music.metachanged");
iF.addAction("fm.last.android.metachanged");
iF.addAction("com.sec.android.app.music.metachanged");
iF.addAction("com.nullsoft.winamp.metachanged");
iF.addAction("com.amazon.mp3.metachanged");
iF.addAction("com.miui.player.metachanged");
iF.addAction("com.real.IMP.metachanged");
iF.addAction("com.sonyericsson.music.metachanged");
iF.addAction("com.rdio.android.metachanged");
iF.addAction("com.samsung.sec.android.MusicPlayer.metachanged");
iF.addAction("com.andrew.apollo.metachanged");
registerReceiver(mReceiver, iF);
Also have a look at this
Much better answer of 123 abc
For simple check whether music is playing or not. Use
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())//it checks whether music is played by Android OS
{
// Something is being played.
}
You should use that like this:
public boolean isMusicRunning(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfos.size(); i++) {
if (procInfos.get(i).processName.equals("com.android.music")) {
Toast.makeText(null, "music is running", Toast.LENGTH_LONG).show();
}
}
}