我正在從MainActivity開始中的Service TrackingService
。從TrackingService
我通過JSONString
到PostData
類。然後我收到服務器的響應direction, route
。我想將這些值傳遞給MainActivity,但我沒有在MainActivity中獲取它們。方向和路線具有值,正在調用,並且正在輸入方法中的此條件if (route != 0) {}
,但MainActivity中的'onNewIntent()'方法未被調用。我該如何解決它以從PostData
類獲得MainActivity
的方向和路線?將數據從班級傳遞到MainActivity
MainActivity類別:
public class MainActivity extends ActionBarActivity implements
AsyncTaskCallback {
private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(this, TrackingService.class);
startService(i);
}
public static Context getAppContext() {
return context;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("dirtRout")) {
String directRoute = extras.getString("dirtRout");
String[] split = directRoute.split(",");
String direc = split[0];
String route1 = split[1];
boolean test = true;
if (test) {
test = false;
System.out.println("test f MainActivity: " + direc + ": "
+ route1);
tvD = (TextView) findViewById(R.id.textDirect);
tvD.setText(direc);
tvR = (TextView) findViewById(R.id.textRoute);
tvR.setText(route1);
}
}
}
}
Trackingservice類:
public class TrackingService extends Service implements AsyncTaskCallback,
LocationListener {
...
@Override
public void onLocationChanged(Location location) {
PostData sender = new PostData(TrackingService.this);
sender.post_data(jSONString, this);
}
}
POSTDATA類:
public class PostData {
String jSONString;
private AsyncTaskCallback callback;
public PostData(AsyncTaskCallback callback) {
this.callback = callback;
}
class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
int route;
String direction;
.....
@Override
protected ArrayList<Integer> doInBackground(String... params) {
......
Gson gson = new Gson();
JSONStore data = gson.fromJson(sb.toString(), JSONStore.class);
route = data.getRoute();
direction = data.getDirection();
}
protected void onPostExecute(ArrayList<Integer> result) {
if (route != 0) {
String directRoute = direction + "," +Integer.toString(route);
Intent intent = new Intent(MainActivity.getAppContext(), MainActivity.class);
intent.putExtra("dirtRout", directRoute);
}
}
}
什麼是您的活動在清單中的launchMode? – yshahak