我正在 onCreate()
中从 MainActivity 启动一个服务 TrackingService
。从 TrackingService
我将 JSONString
传递给 PostData
类。然后我从服务器收到带有方向,路线
的响应。我想将这些值传递给 MainActivity,但我没有在 MainActivity 中获取它们。方向和路线都有值,并且 onPostExecute()
正在被调用,并且方法中的条件 if (route != 0) {}
正在输入,但 'onNewIntent() MainActivity 中的方法未被调用。如何修复它以从 PostData
类获取 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);
}
}
}
}
跟踪服务类:
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);
}
}
}
最佳答案
创建 Intent 后您不会开始 Activity 。从应用程序获取当前的 Activity 并调用 startActivity 方法。
关于android - 将数据从类传递到 MainActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31902156/