Android - 如何在LISENTER的类之间传输数据

时间:2016-04-19 10:39:06

标签: android listener

我有一个从服务器获取json的类“MyGcmListenerService”。我想从json获取String并将其发送到MainActivity并激活一个方法。 有人告诉我,我可以使用Listener和界面。好吧,我真的不知道如何使用它。有人可以帮帮我吗?

这是MyGcmListenerService代码

 package com.world.bolandian.watchmesensor;

 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.Intent;
 import android.media.RingtoneManager;
 import android.net.Uri;
 import android.os.Bundle;
 import android.support.v4.app.NotificationCompat;
 import android.util.Log;

 import com.google.android.gms.gcm.GcmListenerService;

 public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";


/**
 * Called when message is received.
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("typemessage");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        // normal downstream message.
    }

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    sendNotification(message);
    // [END_EXCLUDE]
}
// [END receive_message]

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.
 */
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
            .setContentTitle("GCM Message")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }

 } 

这是MainActivity

   package com.world.bolandian.watchmesensor;

  import android.app.Activity;
  import android.content.Context;
  import android.content.SharedPreferences;
  import android.hardware.Sensor;
  import android.hardware.SensorEvent;
  import android.hardware.SensorEventListener;
  import android.hardware.SensorManager;
  import android.os.Bundle;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.widget.TextView;
  import android.widget.Toast;

  import com.google.gson.Gson;

  public class MainActivity extends Activity implements SensorEventListener, Listen{

Sensor accelerometer;
SensorManager sm;
TextView acceleration;
SendValues sv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sm = (SensorManager)getSystemService(SENSOR_SERVICE);
    accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sm.registerListener(this,accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    acceleration = (TextView)findViewById(R.id.sensorTxt);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onSensorChanged(SensorEvent event) {
    acceleration.setText("X: " + event.values[0] +
            "\nY: " + event.values[1] +
            "\nZ: " + event.values[2]);

    // get the phone number from the login
    SharedPreferences sh = getSharedPreferences("BikePhone", Context.MODE_PRIVATE);
    String phone = sh.getString(Params.PHONE,null);

    if (event.values[0] >=5.000 || (event.values[0] <= -5.000) || (event.values[1] >= 5.000) || (event.values[1] <= -5.000))
    {

        sv = new SendValues(phone,"1");

        Gson g = new Gson();
        String ans = g.toJson(sv,SendValues.class);
        send(sv);
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}


public void send (SendValues sv)
{
    SendThreadCommunication con;
    ServerRequest ser = new ServerRequest();
    ser.setResponse(this);
    Gson gson = new Gson();

    String send = gson.toJson(sv,SendValues.class);

    ser.addParamaters(Params.VALUES, send);
    ser.addServerName(Params.SERVER_URL);
    ser.addServletName(Params.BIKE_TO_USER);
    con = new SendThreadCommunication(ser);
    con.start();
}

@Override
public void good() {

}

@Override
public void notGood() {

}

@Override
public void userGcmNotRegistered() {
    Toast.makeText(getApplication(), "There is some problem, please register again to the App", Toast.LENGTH_LONG).show();
  }
 }

这就是界面

  package com.world.bolandian.watchmesensor;

  public interface Listen {
  public void good();
  public void notGood();
 }

1 个答案:

答案 0 :(得分:0)

更好的方法是使用BroadcastReceivers。您需要先在BroadcastReceivers课程中创建MainActivity,然后在onResume()方法中注册,并在onPause()中取消注册。然后只需发送MyGcmListenerService的广播,例如

Intent intent = new Intent();
intent.setAction("com.world.bolandian.watchmesensor.CUSTOM_ACTION");
sendBroadcast(intent);

注册BroadcastReceivers时,将com.world.bolandian.watchmesensor.CUSTOM_ACTION添加到IntentFilter