3

我想在我的歌曲列表活动中显示列表视图,.. 为此,我创建了 MyService 类,我将用于播放服务。在那个 MyService 类中,我创建了可以在 SDCard 上获取所有可用歌曲的方法。我想通过使用服务在歌曲列表活动的列表视图中显示所有歌曲。

这是我在 songList Activity 中的代码:

private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            objservice = null;
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            objservice = ((MyService.LocalBinder) service).getService();
            adapter = (ListAdapter) objservice.getSongList();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.playlist);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        bindService(new Intent(PlayListActivity.this, MyService.class),
                serviceConnection, BIND_AUTO_CREATE);

        setListAdapter(adapter);
       }

服务类代码:

public class MyService extends Service {

    private MediaPlayer mp = null;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private ListAdapter adapter = null;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return new LocalBinder();
    }

    @Override
    public void onCreate() {

    }

    public class LocalBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public ListAdapter getSongList() {
        final ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

        Cursor cursor = getContentResolver().query(
                android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, null);
        if (cursor == null) {
            // Query Failed , Handle error.
        } else if (!cursor.moveToFirst()) {
            // No media on the device.
        } else {
            int titleColumn = cursor
                    .getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor
                    .getColumnIndexOrThrow(android.provider.MediaStore.Audio.Media.DATA);
            int artistcolumn = cursor
                    .getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
            int durationcolumn = cursor
                    .getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
            int id = cursor
                    .getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            for (int i = 0; i < cursor.getCount(); i++) {
                String thisTitle = cursor.getString(titleColumn);
                String path = cursor.getString(idColumn);
                String artist = cursor.getString(artistcolumn);
                Long duration = cursor.getLong(durationcolumn);
                Utilities objUtilities = new Utilities();
                String timeDuration = objUtilities
                        .milliSecondsToTimer(duration);
                String ID = cursor.getString(id);

                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", thisTitle);
                song.put("songPath", path);
                song.put("artist", artist);
                song.put("duration", timeDuration);
                song.put("id", ID);
                songsList.add(song);
                cursor.moveToNext();
            }
        }

        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);
            // adding HashList to ArrayList
            songsListData.add(song);
        }

        String[] from = { "songTitle", "artist", "duration" };
        int[] to = { R.id.songTitle, R.id.songArtist, R.id.duration };
        return adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, from, to) {
            public long getItemId(int position) {
                return songsListData.indexOf(getItem(position));
            }
        };
    }
}

那么我的错误是什么?

4

2 回答 2

1

我的问题已经解决了。我创建了一种将适配器设置为我的列表视图的方法。我已经将该方法称为连接到我的服务:

public void updateListView() {
        setListAdapter(adapter);
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                int songIndex = (int) id;
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidBuildingMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                in.putExtra("listFlag", 0);
                startActivity(in);

            }
        });
    }

在这里调用这个方法:

public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            objservice = ((MyService.LocalBinder) service).getService();
            adapter = (ListAdapter) objservice.getSongList();
            updateListView(); // here was my problem
        }

这是您可以使用 service 更新 listview 的方式。谢谢。

于 2013-01-11T07:52:45.710 回答
0

我在这个讨论中迟到了。

我通过这种方式来绑定服务。

这是 Client.java 类

package com.example.bindservice.binder;

import java.util.ArrayList;
import java.util.Calendar;

import com.example.bindservice.binder.Server.LocalBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Client extends Activity {

 Handler handler;
 boolean mBounded;
 Server mServer = new Server();
 TextView text;
 ListView list;
 Button button;
 Calendar calendar;
 int minute;
 Intent mIntent;
 ArrayList<String> arlstText;
 ArrayAdapter<String> adapterList;
 static HandlerText handlerAct;
 @Override
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //calendar = new GregorianCalendar();
        text = (TextView)findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
        list = (ListView) findViewById(R.id.list);
      //  minute = calendar.get(Calendar.MINUTE);
     //   Log.i("Log", "Minute is: "+minute);
       // final String[] data = mServer.names;
        handlerAct = new HandlerText();
        arlstText = new  ArrayList<String>();
        adapterList = new ArrayAdapter<String>(Client.this,android.R.layout.simple_list_item_1, arlstText );
       list.setAdapter(adapterList);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
       text.setText(mServer.getTime());

   }
  });
    }

 @Override
 protected void onStart() {
  super.onStart();
  Log.i("Log", "M in onStart");
  mIntent = new Intent(this, Server.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);

 }

 ServiceConnection mConnection = new ServiceConnection() {

  public void onServiceDisconnected(ComponentName name) {
      Log.i("Log", "M in onServiceDisconnected");
   Toast.makeText(Client.this, "Service is disconnected", 1000).show();
   mBounded = false;
   mServer = null;
  }

  public void onServiceConnected(ComponentName name, IBinder service) {
      Log.i("Log", "M in onServiceConnected");
   Toast.makeText(Client.this, "Service is connected", 100).show();
   mBounded = true;
   LocalBinder mLocalBinder = (LocalBinder)service;
   mServer = mLocalBinder.getServerInstance();

   Log.i("Log", "Server Instance is: "+mLocalBinder.getServerInstance().toString());
  }
 };

 @Override
 protected void onStop() {
  super.onStop();
  Log.i("Log", "M in onStop");
  if(mBounded) {
   unbindService(mConnection);
   mBounded = false;
  }
 }
    class HandlerText extends Handler{

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            String text= (String)msg.obj;
            //String text = mServer.a;
            arlstText.add(text);
            adapterList.notifyDataSetChanged(); 
        //  stopService(mIntent);
        //  startService(mIntent);
            //Toast.makeText(Client.this, "activity "+text, 1000).show();
        }
    }
}

这是扩展服务类的 Server.java 类

package com.example.bindservice.binder;

import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class Server extends Service implements Runnable {
    Message msg;
    static String[] names = {
            "Dwight D. Eisenhower",
            "John F. Kennedy",
            "Lyndon B. Johnson",
            "Richard Nixon",
            "Gerald Ford",
            "Jimmy Carter",
            "Ronald Reagan",
            "George H. W. Bush",
            "Bill Clinton",
            "George W. Bush",
            "Barack Obama"
    };
    private boolean isServiceRunning;

    /*Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            msg.obj= (Object)names;
            String[] data = Server.data(names);

            for(int  i = 0 ; i < data.length ; i++)
            {
                Log.i("Log", "data"+data[i]);
            }
            Toast.makeText(Server.this, "Service Started", 1000).show();
        }
    };*/


public static String[] data(String[] name)
{
    name = names;
    return name;
}

 IBinder mBinder = new LocalBinder();

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return 0;
}
 public Server() {
    // TODO Auto-generated constructor stub
     Thread t = new Thread(this);
     t.start();
 }
 @Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    isServiceRunning = false;
    Log.i("Log", "The onDestroy is callled");
}
 @Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    /* ArrayAdapter<String> adapterList = new ArrayAdapter<String>(Server.this,android.R.layout.simple_list_item_1, names);

    list.setAdapter(adapterList);*/
    isServiceRunning = true;

}
 @Override
 public IBinder onBind(Intent intent) {
     Log.i("Log", "M in onBind of server" );
  return mBinder;
 }
 @Override
    public void onRebind(Intent intent) {
        // TODO Auto-generated method stub
        super.onRebind(intent);
        Log.i("Log", "M in onRebind");  
    }
 @Override
public boolean onUnbind(Intent intent) {
    // TODO Auto-generated method stub
    return true;
}
 public class LocalBinder extends Binder {

  public Server getServerInstance() {
      Log.i("Log", "M in getServerInstance of server" );
   return Server.this;
  }
 }

 public String getTime() {
     Log.i("Log", "M in getTime of server class");
  SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  //Log.i("Log", "Time"+mDateFormat.toString());
  return mDateFormat.format(new Date());
 }

@Override
public void run() {
    Log.i("Log", "run");
    int i = 0,ai;
    long millisec = 0,tempmilli;
    while(isServiceRunning)
    //while(millisec != 60000)
    {
        Log.i("Log", "while");
        Log.i("Log", "Its started");

        try {
            /*tempmilli = 10000;
            millisec = millisec + tempmilli;*/
            Thread.sleep(3000);

            for( ai = i ; ai< names.length; ai ++)
            {
                /*msg.obj = names[i];
                Client.handlerAct.sendMessage(msg);
                msg = Message.obtain();*/
                //msg.recycle();
                Log.i("Log", "ai is"+ai);
                Log.i("Log", "i is"+i);
                msg = Client.handlerAct.obtainMessage();
                msg.obj = names[ai];
                Client.handlerAct.sendMessage(msg);
                break;
            }
            i = i+1;
            Log.i("Log", "I outside loop"+i);
            //Message msg = new Message();
            //Message msg = Message.obtain();
            /*msg = handler.obtainMessage();
            msg.obj = "Hi";
            Client.handlerAct.sendMessage(msg);*/
        /*  msg = handler.obtainMessage();
            msg.obj = "Bye";
            Client.handlerAct.sendMessage(msg);*/
            Log.i("Log", "Loop breaked");
            }   
        catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }
}
}

希望这将清除并建立更多的想法。

谢谢

于 2013-01-16T05:35:32.570 回答