2013-01-11 131 views
3

我想在我的歌曲列表活動中顯示listview。爲此,我創建了MyService類,我將用它來播放服務。在那個MyService類中,我創建了一個方法來獲取SDCard上可用的歌曲。我想通過使用服務在songlist Activity的listview中顯示所有那首歌曲。從服務類設置ListView數據Android

這是我在的SongList活動代碼:

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)); 
      } 
     }; 
    } 
} 

那麼,什麼是我的錯誤?

回答

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 
     } 

這是你可以通過使用服務更新列表視圖的方式。感謝名單。

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(); 
     } 
    } 
} 

這裏被延伸服務類

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(); 
     } 
    } 
} 
} 

希望Server.java類,這將明確和建立一些更多的想法。

感謝

+0

樂施會感謝名單..。 。 – zanky