我正在TrackingService
的MainActivity中启动服务onCreate()
。从TrackingService
我正在通过JSONString
到PostData
班级。然后我从服务器获得direction, route
的响应。我想将这些值传递给MainActivity,但我没有在MainActivity中获取它们。方向和路由具有值,并且正在调用onPostExecute()
,并且正在输入方法中的条件if (route != 0) {}
,但未调用MainActivity中的'onNewIntent()'方法。如何修复它以获取MainActivity
类PostData
中的方向和路线?
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);
}
}
}
答案 0 :(得分:2)
创建意图后,您没有开始活动。从应用程序获取当前活动并调用startactivity方法。