如何解决java.lang.RuntimeException:执行停止未恢复的活动

时间:2016-09-09 11:26:54

标签: android android-activity android-service

我得到了java.lang.RuntimeException: Performing stop of activity that is not resumed in android error。我在一个时间间隔内调用我的服务函数,其中包含WebViewActivity的意图,我必须在特定时间停止

这是我的服务:

public class MyService extends Service {

private static String TAG = "MyService";
private Handler webview_handler;
private Runnable runnable;

private final IBinder mBinder = new MyBinder();

boolean mAllowRebind;

//URL to get JSON Array
private static String url = "http://www.planetskool.com/Scripts/json.js";//"http://85.25.195.154/json.js";

//JSON Node Names
private String ARRAY_TITLE = "jsonArray";
private String TAG_JS_FILE = "js_file";

@Override
public void onCreate() {
    webview_handler = new Handler();
    //Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_SHORT).show();
    super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    if (webview_handler != null) {
        webview_handler.removeCallbacks(runnable);
    }
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("MyService", "Service_Started");
    //ToggleData();
    SyncJsonData();
    //Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
    return START_STICKY;
}

@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    //Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_SHORT).show();
    Log.i(TAG, "onStart");
}

public class MyBinder extends Binder {
    public MyService getService() {
        return MyService.this;
    }
}

public boolean SyncJsonData() {
    Log.d("MyService", "Syncing_Data");
    ToggleData();

    try {
        //URL json = new URL("http://www.planetskool.com/App/GetMyBAppJson");
        URL json = new URL("http://www.planetskool.com/Scripts/json.json");
        URLConnection jc = json.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

        String line = reader.readLine();
        //Log.d("CT1", "line = " + line + "\n");
        JSONObject jsonResponse = new JSONObject(line);
        //Log.d("CT1", "jsonResponse = " + jsonResponse + "\n");
        JSONArray jsonArray = jsonResponse.getJSONArray(ARRAY_TITLE);
        Log.d("MyService", "SyncedArray: " + jsonArray);
        //Log.d("CT1", "jsonArray = " + jsonArray + "\n");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            Log.d("ChatThreadSync", "js_file = " + TAG_JS_FILE);
            String jsonFileURL = jsonObject.getString("js_file");
            boolean status = jsonObject.getBoolean("status");
            final int next_call = jsonObject.getInt("next_call") * 1000;
            int time_out = jsonObject.getInt("time_out") * 1000;
            if(status == true){
                Log.d("MyService", "next_call: " + next_call);
                Log.d("MyService", "time_out: " + time_out);

                File file = new File(Environment.getExternalStorageDirectory().toString(), "json.js");
                boolean deleted = file.delete();
                Log.d("MyService", "isFileDeleted: " + deleted);

                new DownloadFileFromURL().execute(jsonFileURL);
                CallWebView(time_out);

                Timer t = new Timer();
                t.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      SyncJsonData();
                                  }
                              },
                        0,
                next_call);
            }
        }
        reader.close();
    } catch (NullPointerException nPE) {

    } catch (Exception e) {

    }
    return true;
}

public void CallWebView(int time_out) {
    Log.d("MyService", "Callin_WebView:");
    //Toast.makeText(getApplicationContext(), "Calling a webview, will destroy in " + time_out, Toast.LENGTH_SHORT).show();
    Intent i = new Intent(this, WebViewActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

    webview_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Toast.makeText(getApplicationContext(), "next_call = " + next_call, Toast.LENGTH_SHORT).show();
            WebViewActivity activity = new WebViewActivity();
            activity.finish();
        }
    }, time_out);
}

public void ToggleData(){
    Log.d("MyService", "Toggle_Mobile_Data:");
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    //wifiManager.setWifiEnabled(true);
    if(wifiManager.isWifiEnabled()) {
        Log.i(TAG, "Wifi_Enabled");
        wifiManager.setWifiEnabled(false);
    }

    ToggleMobileData();
}

public void ToggleMobileData(){
    ConnectivityManager dataManager;
    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Method dataMtd = null;
    try {
        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    dataMtd.setAccessible(true);
    try {
        dataMtd.invoke(dataManager, true);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    Log.i(TAG, "setMobileDataEnabled1");
    final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    Log.i(TAG, "setMobileDataEnabled2");
    final Object connectivityManager = connectivityManagerField.get(conman);
    final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
    Log.i(TAG, "setMobileDataEnabled3");
    final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    try {
        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
        Log.i(TAG, "setMobileDataEnabled4");
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
}

这是我的活动类:

    public class WebViewActivity extends Activity {

    private WebView webView;
    private static ArrayList<Activity> activities=new ArrayList<Activity>();

    public void onCreate(Bundle savedInstanceState) {

        moveTaskToBack(true);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.planetskool.com/Scripts/my_html_page.html");
        Log.d("WebViewActivity", "Calling_MyWebView");
        //Toast.makeText(getApplicationContext(),"Calling a WebView",Toast.LENGTH_LONG).show();    
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

0 个答案:

没有答案