在Nearby Messages API中发送多个消息/字符串

时间:2017-02-13 17:26:04

标签: java android api android-studio google-nearby

我正在尝试使用Nearby Messages API在一个活动(曲目,专辑,艺术家)中发布多个字符串并订阅它们,并让它们在Textview中显示在另一个活动中。当我运行它时,应用程序中只显示一个字符串,它出现在所有3个文本视图中。有没有办法发布多个字符串或消息,以便它们可以同时出现在单独的TextView中?如果我遗漏了任何东西,请告诉我。 首先是出版活动:

     import android.content.BroadcastReceiver;
     import android.content.Context;
     import android.content.Intent;
     import android.content.IntentFilter;
     import android.os.Bundle;
     import android.support.annotation.NonNull;
     import android.support.v7.app.AppCompatActivity;
     import android.util.Log;
     import android.view.View;
     import android.widget.Button;
     import android.widget.TextView;

     import com.google.android.gms.common.ConnectionResult;
     import com.google.android.gms.common.api.GoogleApiClient;
     import com.google.android.gms.nearby.Nearby;
     import com.google.android.gms.nearby.messages.Message;

     import static com.example.mark.prototype9.MainActivity.RETURN;


    public class MusicPlayingActivity extends AppCompatActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener
    {

public static final String TAG = "track";
public static final String TAG1 = "album";
public static final String TAG2 = "artist";

public static final String SERVICECMD = "com.android.music.musicservicecommand";

GoogleApiClient mGoogleApiClient;
Message mActiveMessage, nActiveMessage, oActiveMessage;

TextView artist;
TextView album;
TextView title;
Button songfeed;


private void publish(String message, String message1, String message2) {
    Log.i(TAG, "Publishing message: " + message + message1);
    Log.i(TAG1, "Publishing message: " + message1);
    Log.i(TAG2, "Publishing message: " + message2);
    mActiveMessage = new Message(message.getBytes());
    nActiveMessage = new Message(message1.getBytes());
    oActiveMessage = new Message(message2.getBytes());
    Nearby.Messages.publish(mGoogleApiClient, mActiveMessage);
    Nearby.Messages.publish(mGoogleApiClient, nActiveMessage);
    Nearby.Messages.publish(mGoogleApiClient, oActiveMessage);
    }

private void unpublish() {
    Log.i(TAG, "Unpublishing.");
    Log.i(TAG1, "Unpublishing.");
    Log.i(TAG2, "Unpublishing.");
    if (mActiveMessage != null)
        if(nActiveMessage !=null)
            if(oActiveMessage !=null) {
        Nearby.Messages.unpublish(mGoogleApiClient, mActiveMessage);
        Nearby.Messages.unpublish(mGoogleApiClient, nActiveMessage);
        Nearby.Messages.unpublish(mGoogleApiClient, oActiveMessage);
        mActiveMessage = null;
        nActiveMessage = null;
        oActiveMessage = null;
    }
}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Nearby.MESSAGES_API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .enableAutoManage(this, this)
            .build();

    setContentView(R.layout.activity_music_playing);
    artist = (TextView) findViewById(R.id.artist);
    album = (TextView) findViewById(R.id.album);
    title = (TextView) findViewById(R.id.title);
    songfeed = (Button) findViewById(R.id.songfeed);


    IntentFilter iF = new IntentFilter();
    iF.addAction("com.android.music.metachanged");
    iF.addAction("com.android.music.playstatechanged");
    iF.addAction("com.android.music.playbackcomplete");
    iF.addAction("com.android.music.queuechanged");
    iF.addAction("com.htc.music.metachanged");
    iF.addAction("fm.last.android.metachanged");
    iF.addAction("com.sec.android.app.music.metachanged");            //intentFilters assigned to music-playing activities in other applications
    iF.addAction("com.nullsoft.winamp.metachanged");
    iF.addAction("com.amazon.mp3.metachanged");
    iF.addAction("com.miui.player.metachanged");
    iF.addAction("com.real.IMP.metachanged");
    iF.addAction("com.sonyericsson.music.metachanged");
    iF.addAction("com.rdio.android.metachanged");
    iF.addAction("com.samsung.sec.android.MusicPlayer.metachanged");
    iF.addAction("com.andrew.apollo.metachanged");


    registerReceiver(mReceiver, iF);                                  //BroadcastReceiver listens for data broadcast by other activities


    songfeed.setOnClickListener(new View.OnClickListener(){           //commanding "songfeed" button to return user to MainActivity
        @Override
        public void onClick (View v){
                Intent getResult = new Intent(getApplicationContext(), MainActivity.class);
                startActivityForResult(getResult, RETURN);
            }

    });
}



public BroadcastReceiver mReceiver = new BroadcastReceiver() {       //new instance of BroadcastReceiver

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        String cmd = intent.getStringExtra("command");
        Log.v("tag ", action + " / " + cmd);
        String artists = intent.getStringExtra("artist");            //receiving data through IntentFilters, converting received data to String
        String albums = intent.getStringExtra("album");
        String tracks = intent.getStringExtra("track");
        Log.v("tag", artists + ":" + albums + ":" + tracks);

        artist.setText(artists);
        album.setText(albums);                                       //setting String data to TextView
        title.setText(tracks);

        publish(tracks, albums, artists);


        unregisterReceiver(mReceiver);

    }

  };

@Override
public void onConnected(Bundle connectionHint) {

}

@Override
public void onStop() {
    unpublish();
    super.onStop();
}



@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

 }

订阅活动

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.nearby.Nearby;
    import com.google.android.gms.nearby.messages.Message;
    import com.google.android.gms.nearby.messages.MessageListener;
    import com.google.android.gms.nearby.messages.SubscribeOptions;

    import static com.example.mark.prototype9.MainActivity.RETURN;
    import static com.example.mark.prototype9.MusicPlayingActivity.TAG;
    import static com.example.mark.prototype9.MusicPlayingActivity.TAG1;
    import static com.example.mark.prototype9.MusicPlayingActivity.TAG2;


    public class SubActivity extends AppCompatActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {


GoogleApiClient nGoogleApiClient;
MessageListener mMessageListener, nMessageListener, oMessageListener;
SubscribeOptions options;


TextView track1;
TextView album1;
TextView artist1;

TextView track2;
TextView album2;
TextView artist2;

TextView track3;
TextView album3;
TextView artist3;

Button back;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pub_sub);

    nGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Nearby.MESSAGES_API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .enableAutoManage(this, this)
            .build();

    options = new SubscribeOptions.Builder()
            //.setCallback(myCallback)
            .build();


                //data to receive
    track1 = (TextView) findViewById(R.id.track1);
    album1 = (TextView) findViewById(R.id.album1);
    artist1 = (TextView) findViewById(R.id.artist1);

    track2 = (TextView) findViewById(R.id.track2);
    album2 = (TextView) findViewById(R.id.album2);
    artist2 = (TextView) findViewById(R.id.artist2);

    track3 = (TextView) findViewById(R.id.track3);
    album3 = (TextView) findViewById(R.id.album3);
    artist3 = (TextView) findViewById(R.id.artist3);

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


    //Track
    mMessageListener = new MessageListener() {
        @Override
        public void onFound(Message message) {
            String messageAsString = new String(message.getContent());
            Log.i(TAG, "Found message: " + messageAsString);
            track1.setText("Someone is listening to "+messageAsString);
        }

        @Override
        public void onLost(Message message) {
            String messageAsString = new String(message.getContent());
            Log.i(TAG, "Lost sight of message: " + messageAsString);
        }
    };
    //album
    nMessageListener = new MessageListener() {
        @Override
        public void onFound(Message message1) {
            String messageAsString1 = new String(message1.getContent());
            Log.i(TAG1, "Found message: " + messageAsString1);
            album1.setText("from "+messageAsString1);
        }

        @Override
        public void onLost(Message message1) {
            String messageAsString1 = new String(message1.getContent());
            Log.i(TAG1, "Lost sight of message: " + messageAsString1);
        }
    };
    //artist
    oMessageListener = new MessageListener() {
        @Override
        public void onFound(Message message2) {
            String messageAsString2 = new String(message2.getContent());
            Log.i(TAG2, "Found message: " + messageAsString2);
            artist1.setText("by "+messageAsString2);
        }

        @Override
        public void onLost(Message message2) {
            String messageAsString2 = new String(message2.getContent());
            Log.i(TAG2, "Lost sight of message: " + messageAsString2);
        }
    };



    back.setOnClickListener(new View.OnClickListener(){           
        @Override
        public void onClick (View v){
            Intent getResult = new Intent(getApplicationContext(), MainActivity.class);
            startActivityForResult(getResult, RETURN);
        }
});

}

// Subscribe to receive messages.
private void subscribe() {
    try{
    Log.i(TAG, "Subscribing.");
    Nearby.Messages.subscribe(nGoogleApiClient, mMessageListener, options );
    Nearby.Messages.subscribe(nGoogleApiClient, nMessageListener, options );
    Nearby.Messages.subscribe(nGoogleApiClient, oMessageListener, options );

}
    catch (NullPointerException n){
        n.printStackTrace();
    }
}

private void unsubscribe() {
    Log.i(TAG, "Unsubscribing.");
    Nearby.Messages.unsubscribe(nGoogleApiClient, mMessageListener);
    Nearby.Messages.unsubscribe(nGoogleApiClient, nMessageListener);
    Nearby.Messages.unsubscribe(nGoogleApiClient, oMessageListener);
}




@Override
public void onConnected(Bundle b) {
    subscribe();
}


@Override
public void onStop() {
    unsubscribe();
    super.onStop();
}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

1 个答案:

答案 0 :(得分:0)

您只需要在侦听器上进行一次订阅,并且所有消息都应该传递给OnFound函数。根据数据,您可以区分消息并将数据放在正确的TextView