Что здесь не так, что я не могу связать сервис в Android - PullRequest
0 голосов
/ 21 февраля 2012

Возвращается NullPointerException, когда я нажимаю кнопку воспроизведения, где я хочу связать кнопку остановки со значением метода getCount (), который находится в классе Service, который должен возвращать 1, происходит сбой при нажатии кнопки воспроизведения , Это класс активности:

public class MainMP3 extends Activity{
Button stop;
static final String MEDIA_PATH = new String("/sdcard/");
Button data_display;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mp3interface);
    startService(new Intent(MainMP3.this, ServiceMP3.class));

    stop= (Button) findViewById(R.id.stop);

    // to stop service 
    //stopService(new Intent(MainMP3.this, ServiceMP3.class));

    Button button = (Button)findViewById(R.id.play);
    button.setOnClickListener(new StartClick());  

}

  private ServiceMP3 service = null;

    private ServiceConnection connection = new ServiceConnection() {
        @Override  // Called when connection is made
        public void onServiceConnected(ComponentName cName, IBinder binder) {
            service = ((ServiceMP3.SlowBinder)binder).getService();
        }
        @Override   //
        public void onServiceDisconnected(ComponentName cName) {
            service = null;
        }
    };  

    private class StartClick implements View.OnClickListener {      
        public void onClick(View v) {
            int data = service.getCount();
            stop.setText(Integer.toString(data));
        }
    }
       }

и вот услуга:

public class ServiceMP3 extends Service {

 private static final String MEDIA_PATH = new String("/sdcard/");
 private MediaPlayer mp = new MediaPlayer();
 private List<String> songs = new ArrayList<String>();
 private int currentPosition;
 int count=1;
 private NotificationManager nm;
 private static final int NOTIFY_ID = R.layout.song;


    public int getCount() {return count;}

    @Override
    public void onCreate() {
        super.onCreate();
        BindAllSongs();

        System.out.println(MEDIA_PATH+ songs.get(currentPosition));

        for (int i = 0; i < songs.size(); i++) {
            System.out.println(songs.get(i).toString());
        }

        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            //          playSong(MEDIA_PATH+ songs.get(currentPosition));

            //          Thread thr = new Thread(null, work, "Play Song");
             //         thr.start();

            // Toast.makeText(this, "Service Started",  Toast.LENGTH_SHORT).show();
             //         player = MediaPlayer.create(ServiceMP3.this, R.raw.test);
            //          player.start();
            //          player.setLooping(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this, "Service started...", Toast.LENGTH_LONG).show();
        return Service.START_NOT_STICKY;  
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        mp.stop();
        mp.release();
        nm.cancel(NOTIFY_ID);
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
    }


    public void BindAllSongs() 
    {
        // TODO Auto-generated method stub

         //To hold all the audio files from SDCARD
        File fileListBeforeFiltering = new File(MEDIA_PATH);
        //Filter all the MP# format songs to list out
        //Checking for the MP3 Extension files existence 
            if (fileListBeforeFiltering.listFiles(new    FilterFilesByMp3Extension()).length > 0) 
            {
                //Loop thru all the files filtered and fill them in SongsList view that we have 
                //Defined above.
                for (File file : fileListBeforeFiltering.listFiles(new FilterFilesByMp3Extension())) 
                {
                    //Adding all filtered songs to the list
                        songs.add(file.getName());
                }

        }
    }

     void playSong(String file) {
        try {





                mp.setDataSource(file);

                mp.prepare();
                mp.start();

                mp.setOnCompletionListener(new OnCompletionListener() {

                     public void onCompletion(MediaPlayer arg0) {
                             nextSong();
                     }
             });

        } catch (IOException e) {
                Log.e(getString(R.string.app_name), e.getMessage());
        }
       }


     void nextSong() {
        // Check if last song or not
        if (++currentPosition >= songs.size()) {
                currentPosition = 0;
                nm.cancel(NOTIFY_ID);
        } else {
                playSong(MainMP3.MEDIA_PATH + songs.get(currentPosition));
        }


}

     void prevSong() {
        if (mp.getCurrentPosition() < 3000 && currentPosition >= 1) {
                playSong(MainMP3.MEDIA_PATH + songs.get(--currentPosition));
        } else {
                playSong(MainMP3.MEDIA_PATH + songs.get(currentPosition));
        }
}


    Runnable work = new Runnable() {
        public void run() {

             while (true) { 

                System.out.println("Runnable method....");

            }

        }

    };


    private final IBinder binder = new SlowBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class SlowBinder extends Binder {
        ServiceMP3 getService() {
            return ServiceMP3.this;
        }
    }


}

1 Ответ

5 голосов
/ 16 октября 2012

Сначала попробуйте заменить

startService (новое намерение (MainMP3.this, ServiceMP3.class));

на

bindService (новое намерение (MainMP3.this, ServiceMP3.class));

Прочитайте пожалуйста: Связанные услуги

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...