我有一个名为MainActivity的活动,它使用方法selectItem()进行片段事务。此活动的两个片段名为LocationSendActivity和MapActivty。当MainActivity选择LocationSendActivity时,LocationSendActivity调用名为SendMapData.SendMapData的服务,使用它的对象使用MainActivity的名为selectItem()的方法调用MapActivity,之后显示illegalStateException错误。
... MainActivity
package com.example.map;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
public int n;
private String lat,lng;
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence bartitle;
// private Handler handler;
// private boolean maprefreash;
public static double lat10=0,lng10=0;
FragmentManager fm;
Fragment map = new MapActivity();
Fragment msg = new MessageActivity();
Fragment send = new LocationSendActivity();
Fragment find = new LocationFindActivity();
Fragment set = new SettingActivty();
Fragment dia = new AlertDialogFragment();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
//get data from url
Intent intent = getIntent();
// check if this intent is started via custom scheme link
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
// may be some test here with your custom uri
lat = uri.getQueryParameter("lat1");
lng = uri.getQueryParameter("lng1");
//lat10=Double.parseDouble(lat);
Log.e("LatMain",lat);
Log.e("LngMain",lng);
try{
lat10=Double.parseDouble(lat);
lng10=Double.parseDouble(lng);
}catch(Exception e){
e.printStackTrace();
}
}
//Action bar
ActionBar ab=getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_blue_light)));
bartitle= ab.getTitle();
mPlanetTitles = getResources().getStringArray(R.array.item);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
//set the adapter for list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_item,R.id.textView1, mPlanetTitles));
//set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerLayout.setScrimColor(Color.TRANSPARENT);
mDrawerToggle =new ActionBarDrawerToggle(this,mDrawerLayout,R.drawable.ic_drawer,R.string.drawer_open,
R.string.drawer_close){
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(bartitle);
supportInvalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle("Open Drawer");
supportInvalidateOptionsMenu();
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
selectItem(0);
getSupportActionBar().setTitle("Map");
}
//set dropdown menu navigation in action bar
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
String[] data=getResources().getStringArray(R.array.dropDown);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item,data);
ActionBar.OnNavigationListener navigation=new OnNavigationListener() {
public boolean onNavigationItemSelected(int position, long id) {
// TODO Auto-generated method stub
return false;
}
};
/** Setting dropdown items and item navigation listener for the actionbar */
ab.setListNavigationCallbacks(adapter, navigation);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
public void selectItem(int position) {
n=position;
if(n==5){
lat10=0;lng10=0;
this.finish();
}
fm=getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, map);
ft.addToBackStack(null);
break;
case 1:
ft.replace(R.id.content_frame, msg);
ft.addToBackStack(null);
break;
case 2:
ft.replace(R.id.content_frame, send);
ft.addToBackStack(null);
break;
case 3:
ft.replace(R.id.content_frame, find);
ft.addToBackStack(null);
break;
case 4:
ft.replace(R.id.content_frame, set);
ft.addToBackStack(null);
break;
}
// ft.addToBackStack(null);
ft.commit();
}
public void setTitle(CharSequence title) {
bartitle = title;
getSupportActionBar().setTitle(bartitle);
}
public void onBackPressed(){
super.onBackPressed();
if(n==0){
lat10=0;lng10=0;
this.finish();
}
else{
super.onBackPressed();
selectItem(0);
getSupportActionBar().setTitle("Map");
}
}
}
LocationSendActivity ........
package com.example.map;
import java.util.Calendar;
import org.json.JSONException;
import org.json.JSONObject;
import updatedata.TimeInterval;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LocationSendActivity extends Fragment {
private double latt,lngt;
private TextView tv1,tv2;
private Button btn;
public static CheckBox cb;
private Handler handler;
EditText id,email;
String mob1,lat1,lng1,email1,time;
long total,min;
double val;
// int test;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState){
super.onCreate(savedInstanceState);
latt=MapActivity.latitude;
lngt=MapActivity.longitude;
View v=inflater.inflate(R.layout.locationsend, container, false);
tv1=(TextView)v.findViewById(R.id.textView3);
tv2=(TextView)v.findViewById(R.id.textView4);
id=(EditText)v.findViewById(R.id.editText1);
email=(EditText)v.findViewById(R.id.editText2);
btn=(Button)v.findViewById(R.id.button1);
cb=(CheckBox)v.findViewById(R.id.checkBox1);
handler=new Handler();
//get time from time interval
min=TimeInterval.time;
if(min == 1){
val=0.5*60;
}else if(min == 2){
val=1*60;
}else if(min == 3){
val=3*60;
}else if(min == 4){
val=5*60;
}else if(min == 5){
val=15*60;
}
else{
val=0.5*60;
}
total=(long) (val*1000);
Log.e("Seconds", String.valueOf(total));;
tv1.setText(String.valueOf(latt));
tv2.setText(String.valueOf(lngt));
lat1=String.valueOf(latt);
lng1=String.valueOf(lngt);
//Button for send data
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setData();
time= java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Log.e("mob,lat,lng", mob1+" "+lat1+" "+lng1);
new SendData(mob1,lat1,lng1,email1,time).execute();
}
});
//checkbox for send data in interval
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(cb.isChecked()){
MapActivity map=new MapActivity();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft1 = fm.beginTransaction();
ft1.replace(R.id.content_frame, map);
ft1.addToBackStack(null);
ft1.commit();
getActivity().startService(new Intent(getActivity(),SendMapData.class));
// handler.postDelayed(runnable, 1000);
}else{
getActivity().stopService(new Intent(getActivity(),SendMapData.class));
// handler.removeCallbacks(runnable,null);
}
}
});
return v;
}
/* Runnable runnable = new Runnable() {
@Override
public void run() {
// do what you need to do
// new sendMapData(mob1,lat1,lng1,email1,time);
new SendData(mob1,lat1,lng1,email1,time).execute();
// and here comes the "trick"
handler.postDelayed(this, total);
}
}; */
protected void setData() {
// TODO Auto-generated method stub
mob1=id.getText().toString();
// mob.setText("");
email1=email.getText().toString();
// email.setText("");
}
class SendData extends AsyncTask<String, String, String>{
String mob2,email2,lat2,lng2,time2,suc;
int success,val;
public SendData(String mob, String lat,String lng, String email,String time) {
// TODO Auto-generated constructor stub
this.mob2=mob;
this.email2=email;
this.time2=time;
this.lat2=lat;
this.lng2=lng;
}
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
FunctionCall fc=new FunctionCall();
JSONObject jo=fc.sendData(mob2, lat2, lng2, email2, time2 );
try{
success=jo.getInt("success");
// val=success.to
// Log.e("success", succ);
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (success==1){
Toast.makeText(getActivity(),"Data Inserted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(),"Data Not Inserted", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
... SendMapData
package com.example.map;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class SendMapData extends Service {
private Handler handler;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
handler=new Handler();
MainActivity ma=new MainActivity();
ma.selectItem(0);
Toast.makeText(this, "Hold Map To Send Updated Data", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
//doSomethingRepeatedly();
return START_STICKY;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
// do what you need to do
// new sendMapData(mob1,lat1,lng1,email1,time);
// new SendData(mob1,lat1,lng1,email1,time).execute();
// and here comes the "trick"
Toast.makeText(getApplication(), "Send Updated Data", Toast.LENGTH_LONG).show();
handler.postDelayed(this, 10000);
}
};
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable,null);
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
logcat的
01-10 16:19:44.391: E/AndroidRuntime(15320): java.lang.RuntimeException: Unable to start service com.example.map.SendMapData@32657128 with Intent { cmp=com.example.map/.SendMapData }: java.lang.IllegalStateException: Activity has been destroyed
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3071)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.app.ActivityThread.access$3600(ActivityThread.java:127)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2098)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.os.Looper.loop(Looper.java:123)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.app.ActivityThread.main(ActivityThread.java:4635)
01-10 16:19:44.391: E/AndroidRuntime(15320): at java.lang.reflect.Method.invokeNative(Native Method)
01-10 16:19:44.391: E/AndroidRuntime(15320): at java.lang.reflect.Method.invoke(Method.java:521)
01-10 16:19:44.391: E/AndroidRuntime(15320): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
01-10 16:19:44.391: E/AndroidRuntime(15320): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
01-10 16:19:44.391: E/AndroidRuntime(15320): at dalvik.system.NativeStart.main(Native Method)
01-10 16:19:44.391: E/AndroidRuntime(15320): Caused by: java.lang.IllegalStateException: Activity has been destroyed
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1358)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
01-10 16:19:44.391: E/AndroidRuntime(15320): at com.example.map.MainActivity.selectItem(MainActivity.java:198)
01-10 16:19:44.391: E/AndroidRuntime(15320): at com.example.map.SendMapData.onStartCommand(SendMapData.java:23)
01-10 16:19:44.391: E/AndroidRuntime(15320): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3061)