Java 如何发送字符串
我目前正在使用WifiP2pService进行一个项目,并在Wifi上连接每个设备。我不太清楚如何使这些设备相互连接,以便它们可以一起播放同一首歌曲 目前,我已经设置了聊天片段,这样他们就可以相互通信,设备也可以连接。现在我想让它,如果你是组的所有者,mediaID字符串被发送到客户端,他们能够获得mediaID并播放相同的歌曲 这是我的音乐实践课Java 如何发送字符串,java,android,mobile,android-wifi,Java,Android,Mobile,Android Wifi,我目前正在使用WifiP2pService进行一个项目,并在Wifi上连接每个设备。我不太清楚如何使这些设备相互连接,以便它们可以一起播放同一首歌曲 目前,我已经设置了聊天片段,这样他们就可以相互通信,设备也可以连接。现在我想让它,如果你是组的所有者,mediaID字符串被发送到客户端,他们能够获得mediaID并播放相同的歌曲 这是我的音乐实践课 package com.example.android.uamp.ui; import android.app.FragmentTransacti
package com.example.android.uamp.ui;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.media.MediaBrowserCompat;
import android.text.TextUtils;
import android.util.Log;
import com.example.android.uamp.R;
import com.example.android.uamp.utils.LogHelper;
/**
* Main activity for the music player.
* This class hold the MediaBrowser and the MediaController instances. It will create a MediaBrowser
* when it is created and connect/disconnect on start/stop. Thus, a MediaBrowser will be always
* connected while this activity is running.
*/
public class MusicPlayerActivity extends BaseActivity
implements MediaBrowserFragment.MediaFragmentListener {
private static final String TAG = LogHelper.makeLogTag(MusicPlayerActivity.class);
private static final String SAVED_MEDIA_ID="com.example.android.uamp.MEDIA_ID";
private static final String FRAGMENT_TAG = "uamp_list_container";
public static final String EXTRA_START_FULLSCREEN =
"com.example.android.uamp.EXTRA_START_FULLSCREEN";
/**
* Optionally used with {@link #EXTRA_START_FULLSCREEN} to carry a MediaDescription to
* the {@link FullScreenPlayerActivity}, speeding up the screen rendering
* while the {@link android.support.v4.media.session.MediaControllerCompat} is connecting.
*/
public static final String EXTRA_CURRENT_MEDIA_DESCRIPTION =
"com.example.android.uamp.CURRENT_MEDIA_DESCRIPTION";
private Bundle mVoiceSearchParams;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogHelper.d(TAG, "Activity onCreate");
setContentView(R.layout.activity_player);
initializeToolbar();
initializeFromParams(savedInstanceState, getIntent());
// Only check if a full screen player is needed on the first time:
if (savedInstanceState == null) {
startFullScreenActivityIfNeeded(getIntent());
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
String mediaId = getMediaId();
if (mediaId != null) {
outState.putString(SAVED_MEDIA_ID, mediaId);
}
super.onSaveInstanceState(outState);
}
@Override
public void onMediaItemSelected(MediaBrowserCompat.MediaItem item) {
Log.e(TAG, "onMediaItemSelected, mediaId=" + item.getMediaId());
if (item.isPlayable()) {
getSupportMediaController().getTransportControls()
.playFromMediaId(item.getMediaId(), null);
} else if (item.isBrowsable()) {
navigateToBrowser(item.getMediaId());
} else {
LogHelper.w(TAG, "Ignoring MediaItem that is neither browsable nor playable: ",
"mediaId=", item.getMediaId());
}
}
@Override
public void setToolbarTitle(CharSequence title) {
LogHelper.d(TAG, "Setting toolbar title to ", title);
if (title == null) {
title = getString(R.string.app_name);
}
setTitle(title);
}
@Override
protected void onNewIntent(Intent intent) {
LogHelper.d(TAG, "onNewIntent, intent=" + intent);
initializeFromParams(null, intent);
startFullScreenActivityIfNeeded(intent);
}
private void startFullScreenActivityIfNeeded(Intent intent) {
if (intent != null && intent.getBooleanExtra(EXTRA_START_FULLSCREEN, false)) {
Intent fullScreenIntent = new Intent(this, FullScreenPlayerActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(EXTRA_CURRENT_MEDIA_DESCRIPTION,
intent.getParcelableExtra(EXTRA_CURRENT_MEDIA_DESCRIPTION));
startActivity(fullScreenIntent);
}
}
protected void initializeFromParams(Bundle savedInstanceState, Intent intent) {
String mediaId = null;
// check if we were started from a "Play XYZ" voice search. If so, we save the extras
// (which contain the query details) in a parameter, so we can reuse it later, when the
// MediaSession is connected.
if (intent.getAction() != null
&& intent.getAction().equals(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH)) {
mVoiceSearchParams = intent.getExtras();
LogHelper.d(TAG, "Starting from voice search query=",
mVoiceSearchParams.getString(SearchManager.QUERY));
} else {
if (savedInstanceState != null) {
// If there is a saved media ID, use it
mediaId = savedInstanceState.getString(SAVED_MEDIA_ID);
}
}
navigateToBrowser(mediaId);
}
private void navigateToBrowser(String mediaId) {
LogHelper.d(TAG, "navigateToBrowser, mediaId=" + mediaId);
MediaBrowserFragment fragment = getBrowseFragment();
if (fragment == null || !TextUtils.equals(fragment.getMediaId(), mediaId)) {
fragment = new MediaBrowserFragment();
fragment.setMediaId(mediaId);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(
R.animator.slide_in_from_right, R.animator.slide_out_to_left,
R.animator.slide_in_from_left, R.animator.slide_out_to_right);
transaction.replace(R.id.container, fragment, FRAGMENT_TAG);
// If this is not the top level media (root), we add it to the fragment back stack,
// so that actionbar toggle and Back will work appropriately:
if (mediaId != null) {
transaction.addToBackStack(null);
}
transaction.commit();
}
}
public String getMediaId() {
MediaBrowserFragment fragment = getBrowseFragment();
if (fragment == null) {
return null;
}
return fragment.getMediaId();
}
private MediaBrowserFragment getBrowseFragment() {
return (MediaBrowserFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
}
@Override
protected void onMediaControllerConnected() {
if (mVoiceSearchParams != null) {
// If there is a bootstrap parameter to start from a search query, we
// send it to the media session and set it to null, so it won't play again
// when the activity is stopped/started or recreated:
String query = mVoiceSearchParams.getString(SearchManager.QUERY);
getSupportMediaController().getTransportControls()
.playFromSearch(query, mVoiceSearchParams);
mVoiceSearchParams = null;
}
getBrowseFragment().onConnected();
}
}
这是我的聊天管理课
package com.example.android.uamp.PhoneSync;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* Handles reading and writing of messages with socket buffers. Uses a Handler
* to post messages to UI thread for UI updates.
*/
public class ChatManager implements Runnable {
private Socket socket = null;
private Handler handler;
public ChatManager(Socket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
private InputStream iStream;
private OutputStream oStream;
private static final String TAG = "ChatHandler";
@Override
public void run() {
try {
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytes;
handler.obtainMessage(PhoneSync.MY_HANDLE, this)
.sendToTarget();
while (true) {
try {
// Read from the InputStream
bytes = iStream.read(buffer);
if (bytes == -1) {
break;
}
// Send the obtained bytes to the UI Activity
Log.d(TAG, "Rec:" + String.valueOf(buffer));
handler.obtainMessage(PhoneSync.MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] buffer) {
try {
oStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
}
我的客户端套接字处理程序
package com.example.android.uamp.PhoneSync;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
public class ClientSocketHandler extends Thread {
private static final String TAG = "ClientSocketHandler";
private Handler handler;
private ChatManager chat;
private InetAddress mAddress;
public ClientSocketHandler(Handler handler, InetAddress groupOwnerAddress) {
this.handler = handler;
this.mAddress = groupOwnerAddress;
}
@Override
public void run() {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
PhoneSync.SERVER_PORT), 5000);
Log.d(TAG, "Launching the I/O handler");
chat = new ChatManager(socket, handler);
new Thread(chat).start();
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
}
public ChatManager getChat() {
return chat;
}
}
我的组所有者套接字处理程序
package com.example.android.uamp.PhoneSync;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* The implementation of a ServerSocket handler. This is used by the wifi p2p
* group owner.
*/
public class GroupOwnerSocketHandler extends Thread {
ServerSocket socket = null;
private final int THREAD_COUNT = 10;
private Handler handler;
private static final String TAG = "GroupOwnerSocketHandler";
public GroupOwnerSocketHandler(Handler handler) throws IOException {
try {
socket = new ServerSocket(4545);
this.handler = handler;
Log.d("GroupOwnerSocketHandler", "Socket Started");
} catch (IOException e) {
e.printStackTrace();
pool.shutdownNow();
throw e;
}
}
/**
* A ThreadPool for client sockets.
*/
private final ThreadPoolExecutor pool = new ThreadPoolExecutor(
THREAD_COUNT, THREAD_COUNT, 10, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
@Override
public void run() {
while (true) {
try {
// A blocking operation. Initiate a ChatManager instance when
// there is a new connection
pool.execute(new ChatManager(socket.accept(), handler));
Log.d(TAG, "Launching the I/O handler");
} catch (IOException e) {
try {
if (socket != null && !socket.isClosed())
socket.close();
} catch (IOException ioe) {
}
e.printStackTrace();
pool.shutdownNow();
break;
}
}
}
}
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.example.android.uamp.R;
/**
* This fragment handles chat related UI which includes a list view for messages
* and a message entry field with send button.
*/
public class WiFiChatFragment extends Fragment {
private View view;
private ChatManager chatManager;
private TextView chatLine;
private ListView listView;
ChatMessageAdapter adapter = null;
private List<String> items = new ArrayList<String>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_chat, container, false);
chatLine = (TextView) view.findViewById(R.id.txtChatLine);
listView = (ListView) view.findViewById(android.R.id.list);
adapter = new ChatMessageAdapter(getActivity(), android.R.id.text1,
items);
listView.setAdapter(adapter);
view.findViewById(R.id.button1).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (chatManager != null) {
chatManager.write(chatLine.getText().toString()
.getBytes());
pushMessage("Me: " + chatLine.getText().toString());
chatLine.setText("");
chatLine.clearFocus();
}
}
});
return view;
}
public interface MessageTarget {
public Handler getHandler();
}
public void setChatManager(ChatManager obj) {
chatManager = obj;
}
public void pushMessage(String readMessage) {
adapter.add(readMessage);
adapter.notifyDataSetChanged();
}
/**
* ArrayAdapter to manage chat messages.
*/
public class ChatMessageAdapter extends ArrayAdapter<String> {
List<String> messages = null;
public ChatMessageAdapter(Context context, int textViewResourceId,
List<String> items) {
super(context, textViewResourceId, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
String message = items.get(position);
if (message != null && !message.isEmpty()) {
TextView nameText = (TextView) v
.findViewById(android.R.id.text1);
if (nameText != null) {
nameText.setText(message);
if (message.startsWith("Me: ")) {
nameText.setTextAppearance(getActivity(),
R.style.TextAppearance_AppCompat_Large);
} else {
nameText.setTextAppearance(getActivity(),
R.style.TextAppearance_AppCompat_Headline);
}
}
}
return v;
}
}
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Buddy: " + readMessage);
break;
case MY_HANDLE:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
@Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
@Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo) {
Thread handler = null;
/*
* The group owner accepts connections using a server socket and then spawns a
* client socket for every client. This is handled by {@code
* GroupOwnerSocketHandler}
*/
if (p2pInfo.isGroupOwner) {
Log.d(TAG, "Connected as group owner");
try {
handler = new GroupOwnerSocketHandler(
((MessageTarget) this).getHandler());
handler.start();
} catch (IOException e) {
Log.d(TAG,
"Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.d(TAG, "Connected as peer");
handler = new ClientSocketHandler(
((MessageTarget) this).getHandler(),
p2pInfo.groupOwnerAddress);
handler.start();
}
chatFragment = new WiFiChatFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_root, chatFragment).commit();
statusTxtView.setVisibility(View.GONE);
}
public void appendStatus(String status) {
setContentView(R.layout.main);
statusTxtView = (TextView) findViewById(R.id.status_text);
String current = statusTxtView.getText().toString();
statusTxtView.setText(current + "\n" + status);
}
}