我正在开发一个播放从播放列表中选择的音乐的应用程序,此通知中会显示该歌曲的名称。如截图所示,点击时会有一个停止按钮,音乐将停止播放(虽然起初我尝试使用简单的吐司进行实验,如下面的代码所示,但是徒劳无功)。我无法做到这一点。
这是我的代码
public class MusicFragment extends Fragment implements OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> adapter ;
ListAdapter listAdapter;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title="MultiPlayer";
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MusicFragment.class.getSimpleName();
//private Context _context = this;
public static int selected_item=-1;
Uri uri;
public static final String NOTIFY_PREVIOUS = "com.multiplayer.previous";
//public static final String NOTIFY_DELETE = "com.tutorialsface.audioplayer.delete";
//public static final String NOTIFY_PAUSE = "com.tutorialsface.audioplayer.pause";
//public static final String NOTIFY_PLAY = "com.tutorialsface.audioplayer.play";
public static final String NOTIFY_NEXT = "com.multiplayer.next";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_music, container, false);
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)rootView.findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// _context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)rootView.findViewById(R.id.play);
back = (ImageButton)rootView.findViewById(R.id.prev);
next = (ImageButton)rootView.findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActivity().getActionBar();
//bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
EditText editText = new EditText(getActivity().getApplicationContext());
getActivity().getActionBar().setCustomView(editText);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
//listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
//searchAdapter=new CustomListAdapter(_context,items);
//listAdapter=new ListAdapter(_context,listSoundNames,items);
listAdapter=new ListAdapter(getActivity().getApplicationContext(),listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//////////////////changing list item background on click///////////////////
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
uri = Uri.parse(listTest.get(position).toString());
//accessing song path
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
//title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getActivity().getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
///////////////
title = uri.getLastPathSegment();//getting the name of the file from the filepath
showNotification();
/////////////
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
return rootView;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void showNotification(){
// define sound URI, the sound to be played when there's a notification
//Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//Intent next = new Intent("com.multiplayer.ACTION_PLAY");
//PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 100, next, 0);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(getActivity().getApplicationContext(), NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 100, intent, 0);
//PendingIntent pIntent = PendingIntent.getActivity(getActivity().getApplicationContext(), 0, intent, 0);
//PendingIntent pIntent2 = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, next, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
Notification mNotification = new Notification.Builder(getActivity().getApplicationContext()).setContentTitle("Now Playing")
.setContentText(title)
.setSmallIcon(R.drawable.play)
//.addAction(R.drawable.prev, "Previous", pIntent)
// .addAction(R.drawable.next, "Next", pIntent2)
//.setColor(Color.BLUE)
.setContentIntent(pIntent)
.setShowWhen(false)//hide time
.build();
RemoteViews notificationView = new RemoteViews(getActivity().getPackageName(), R.layout.activity_thanks);
mNotification.contentView = notificationView;
mNotification.contentIntent = pIntent;
mNotification.flags |= Notification.FLAG_NO_CLEAR;
//this is the intent that is supposed to be called when the button is clicked
//Intent switchIntent = new Intent(getActivity().getApplicationContext(), NotificationReceiver.class);
// PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.button1, pIntent);
notificationView.setTextColor(R.id.text, Color.BLACK);
//notificationView.setTextViewTextSize(R.id.text, "20dp", 20);
notificationView.setTextViewText(R.id.text, title+"\n");
notificationManager.notify(1, mNotification);
intent.setAction("com.example.app.ACTION_STOP");
//String action = intent.getAction();
/*if(action.equalsIgnoreCase("com.example.app.ACTION_STOP")){
// do your stuff to play action;
Toast.makeText(getActivity().getApplicationContext(), "music ", Toast.LENGTH_SHORT).show();
}*/
///////////////////////////////
AudioPlayerBroadcastReceiver broadcastReceiver = new AudioPlayerBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("com.example.app.ACTION_STOP");
// register the receiver
registerReceiver(broadcastReceiver, intentFilter);
///////////////////////////////
}
private void registerReceiver(
AudioPlayerBroadcastReceiver broadcastReceiver,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getApplicationContext(), "music stopped", Toast.LENGTH_SHORT).show();//sometimes showing
//mp.stop();///not working, creating problem in the whole app
}
public void cancelNotification(int notificationId){
if (Context.NOTIFICATION_SERVICE!=null) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getActivity().getApplicationContext().getSystemService(ns);
nMgr.cancel(notificationId);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(getActivity().getApplicationContext(), "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(getActivity().getApplicationContext(), "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
selected_item=index;
listAdapter.notifyDataSetChanged();//shifting the highlight to the song played
}
else
{
index = (list.getAdapter().getCount()-1)-1;
selected_item=index;
listAdapter.notifyDataSetChanged();
}
uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
} 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();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
title = uri.getLastPathSegment();
showNotification();
Toast.makeText(getActivity().getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
selected_item=index;
listAdapter.notifyDataSetChanged();
//Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
} 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();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
title = uri.getLastPathSegment();
showNotification();
Toast.makeText(getActivity().getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onStop() {
super.onStop();
Toast.makeText(getActivity().getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
cancelNotification(0);
}
@Override
public void onResume() {
super.onResume();
if(mp.isPlaying())
{
Toast.makeText(getActivity().getApplicationContext(), "started", Toast.LENGTH_LONG).show();
showNotification();
}
}
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
mp.stop();
mp.reset();
index = index +1;
selected_item=index;
listAdapter.notifyDataSetChanged();
//Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
} 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();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
title = uri.getLastPathSegment();
showNotification();
Toast.makeText(getActivity().getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
//play.setImageResource(R.drawable.play);
}
}