处理remoteview android通知上的按钮

处理remoteview android通知上的按钮,android,android-notifications,android-remoteview,Android,Android Notifications,Android Remoteview,我正在开发一个应用程序,它可以播放从播放列表中选择的音乐,歌曲的名称会显示在此通知中。如屏幕截图所示,在单击时有一个停止按钮,音乐将停止播放(虽然起初我尝试使用下面代码中编写的简单祝酒词进行试验,但徒劳)。我不能这样做 这是我的密码 public class MusicFragment extends Fragment implements OnClickListener, OnCompletionListener { ListView list; ArrayAdapter&l

我正在开发一个应用程序,它可以播放从播放列表中选择的音乐,歌曲的名称会显示在此通知中。如屏幕截图所示,在单击时有一个停止按钮,音乐将停止播放(虽然起初我尝试使用下面代码中编写的简单祝酒词进行试验,但徒劳)。我不能这样做

这是我的密码

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);
    }
}
公共类MusicFragment扩展片段实现OnClickListener、OnCompletionListener{
列表视图列表;
阵列适配器;
列表适配器列表适配器;
阵列列表测试;
ArrayList声音名称;
图像按钮播放、停止、后退、下一步;
字符串songpath,song,title=“多人游戏”;
int索引,当前位置;
文件[]列表文件;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar;
私有布尔状态=false;
私有静态int save=-1;
整数计数=0;
私有静态最终字符串标记=MusicFragment.class.getSimpleName();
//私有上下文_Context=this;
公共静态int selected_item=-1;
Uri;
公共静态最终字符串NOTIFY_PREVIOUS=“com.multiplayer.PREVIOUS”;
//公共静态最终字符串NOTIFY_DELETE=“com.tutorialsface.audioplayer.DELETE”;
//公共静态最终字符串NOTIFY_PAUSE=“com.tutorialsface.audioplayer.PAUSE”;
//公共静态最终字符串NOTIFY_PLAY=“com.tutorialsface.audioplayer.PLAY”;
公共静态最终字符串NOTIFY_NEXT=“com.multiplayer.NEXT”;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment\u music,container,false);
mp=新媒体播放器();
mp2=新媒体播放器();
mp.setOnCompletionListener(此);
list=(ListView)rootView.findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE\u MODE\u SINGLE);
//_context=这个;
listTest=newArrayList();
listSoundNames=newArrayList();
play=(ImageButton)rootView.findviewbyd(R.id.play);
后退=(ImageButton)rootView.findViewById(R.id.prev);
next=(ImageButton)rootView.findviewbyd(R.id.next);
//添加侦听器
play.setOnClickListener(这个);
back.setOnClickListener(this);
next.setOnClickListener(this);
//操作栏控件
bar=getActivity().getActionBar();
//杆件退根拉深(新的彩色拉深(Color.parseColor(#DF0174”));
//setIcon(新的ColorDrawable(getResources().getColor(android.R.color.transparent));
EditText EditText=新的EditText(getActivity().getApplicationContext());
getActivity().getActionBar().setCustomView(编辑文本);
扫描仪(“/sdcard/”;//存储路径
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*为歌曲添加监听器*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
如果(listTest.size()!=0)
{
//listAdapter=new ArrayAdapter(MainActivity.this、R.layout.simplerow、listSoundNames);
//searchAdapter=新的CustomListAdapter(_上下文,项);
//listAdapter=新的listAdapter(_上下文、ListSoundName、项);
listAdapter=新的listAdapter(getActivity().getApplicationContext(),listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(新的OnItemClickListener()
{
public void onItemClick(AdapterView父对象、视图、整型位置、长id)
{
//////////////////单击更改列表项背景///////////////////
//名单.选举(职位);
view.setSelected(true);
///////////////////问题/////////////
对于(int a=0;a