2017-09-04 17 views
-1

Android策略如果廣播工作超過10秒,將發生ANR對話框。爲什麼在Android上發生ANR Intent消息廣播?

所以,我覺得我的播出工作超過10秒。因爲許多人在播放這個節目

我的廣播當我的設備上的CONNECTIVITY_ACTION

@Override 
public void onReceive(Context context, Intent intent) { 

    String action = intent.getAction(); 

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 

    int iNetworkType = (activeNetwork == null) ?-1: activeNetwork.getType(); //null check 

    if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 
     new getPubIp().execute(); //Execute AsyncTask 

     ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 

     if (iNetworkType == connectivityManager.TYPE_ETHERNET) {//connect ethernet 
      EthernetConnectTimeDB ethernet; 
      ethernet = new EthernetConnectTimeDB(); 
      ethernet.start(); //DB Insert work. 

      SystemClock.sleep(500); // sleep 
      MainActivity.display("value", "value", value"); //display UI 
     } 
    } 
} 

這個接收器很多工作。數據庫工作,顯示工作,asynctask工作。

如何解決在Android上發生ANR對話框?

謝謝。

回答

0

廣播接收器需要非常快。你有大約2秒鐘,然後你的應用程序被殺害。如果你需要比這更長的時間,你需要啓動一個服務,然後在那裏做。一個體面的經驗法則是,如果您出於任何原因需要啓動線程或AsyncTask,則需要啓動服務。其次,你絕不應該在BroadcastReceiver上睡覺。這發生在主線程上。你會凍結你的應用程序,並可能導致這個問題。

第三,你在MainActivity上訪問靜態函數嗎?這幾乎肯定是錯誤的。因爲它實際上以這種方式將數據發送到主要活動,您必須持有一個內存泄漏的靜態實例。它永遠不應該做的事情。

你需要研究如何正確書寫BraodcastReceiver,你打破了幾乎所有的規則。