2016-04-19 76 views
0

我有從服務器獲取json的類「MyGcmListenerService」。我想從JSON中獲取字符串並將其發送到MainActivity並激活一個方法。 我被告知我可以使用Listener和界面。以及我真的不知道如何使用它。誰能幫幫我嗎?Android - 如何使用LISENTER在類之間傳輸數據

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

回答

0

更好的方法是使用BroadcastReceivers。您需要首先在MainActivity課程中創建一個BroadcastReceivers,並將其註冊爲onResume()方法,並在onPause()中取消其註冊。然後只需從您的MyGcmListenerService發送廣播,例如

和註冊BroadcastReceivers時添加com.world.bolandian.watchmesensor.CUSTOM_ACTION到IntentFilter