2013-05-16 73 views
-1

我正在開發一款應用程序,它需要運行該服務以定期更新。但問題是,在Micromax手機中測試應用程序時,它會給出如下錯誤。服務不適用於micromax手機

05-10 12:32:28.174: E/AndroidRuntime(27143): FATAL EXCEPTION: main 
05-10 12:32:28.174: E/AndroidRuntime(27143): java.lang.RuntimeException: Unable to create service com.ministry.ensing119app.news.UpdateService: android.os.NetworkOnMainThreadException 

該應用程序可以在三星和索尼上完美運行。異步不能在服務中運行。請給出一些關於如何解決這個問題的建議。

UpdateService.java

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.media.Ringtone; 
import android.media.RingtoneManager; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.net.Uri; 
import android.os.IBinder; 
import android.preference.PreferenceManager; 
import android.util.Log; 

public class UpdateService extends Service{ 

    private Updater updater; 
    private static final String TAG ="Background"; 
    private boolean isRunning = false; 
    public static int id= 1; 
    NotificationManager NM; 
    String cid; 
    static final long DELAY = 30000; 


    JSONArray updates= null; 


    @Override 
    public IBinder onBind(Intent intent) { 


     return null; 
    } 

    public boolean isRunning(){ 
     return this.isRunning; 
    } 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
     ConnectivityManager connectivityManager 
     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 

       Message msg = new Message(); 
       Integer i = msg.products.length()-1; 
       Log.d("value", i.toString()); 
       try { 
        JSONObject c1 = msg.products.getJSONObject(i); 
        cid = c1.getString("cid"); 
        Log.d("value of cid",cid.toString()); 
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(UpdateService.this.getApplicationContext()); 
        Editor edit = prefs.edit(); 
        edit.putString("old", cid); 
        edit.commit(); 
       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
      } 

     } 
//  updater = new Updater(); 

    @Override 
    public synchronized void onStart(Intent intent, int startId) { 
     // TODO Auto-generated method stub 
     updater = new Updater(); 
     super.onStart(intent, startId); 

     if(!this.isRunning){ 
      updater.start(); 
      this.isRunning = true; 
     } 
     Log.d(TAG,"ON START"); 


    } 
    @Override 
    public synchronized void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     if(this.isRunning){ 
      updater.interrupt(); 

     } 
     updater = null; 
     Log.d(TAG, "ON DESTOY"); 

    } 

    class Updater extends Thread{ 

     public void run(){ 
      isRunning = true; 
      while (isRunning) { 
        try { 
         Log.d(TAG, "update is running"); 

         JSONParser jparser = new JSONParser(); 
         JSONObject json1 = jparser.getJSONFromUrl("http://ensignweb.com/sandbox/app/comment11.php"); 
         updates = json1.getJSONArray("products"); 
         JSONObject update = updates.getJSONObject(updates.length()-1); 
         cid= update.getString("cid"); 
         SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(UpdateService.this.getApplicationContext()); 
         String old1 = prefs.getString("old", ""); 
         if(!(old1.equals(cid))){ 
          SharedPreferences.Editor change = prefs.edit(); 
          old1 = cid.toString(); 
          change.putString("old", old1); 
          change.commit(); 
          Intent intent = new Intent(UpdateService.this,NewsActivity.class); 
          PendingIntent pIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0); 
          Notification n = new Notification(R.drawable.ic_launcher, "new update arrived", System.currentTimeMillis()); 
          n.setLatestEventInfo(getApplicationContext(), "Update", "new update arrived", pIntent); 
          n.flags = Notification.FLAG_AUTO_CANCEL; 
          NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
          NM.notify(id,n); 

          try{ 
           Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
           Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); 
           r.play(); 
          }catch(Exception e){ 
           e.printStackTrace(); 
          } 
          Log.d("Change","the old value changed"); 
         }else{ 
            Thread.sleep(DELAY); 
         }      
        } catch (InterruptedException e) { 
         isRunning = false; 
        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
      } 
     } 
    } 
} 

Message.java

public class Message { 

    public static String url = "http://abc.com/sandbox/app/comment11.php"; 

    // JSON Node names 
    protected static final String TAG_PRODUCTS = "products"; 
    protected static final String TAG_CID = "cid"; 
    public static final String TAG_NAME = "name"; 

    // contacts JSONArray 
    JSONArray products = null; 
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); 
    public Message() { 
        // Creating JSON Parser instance 
        JSONParser jParser = new JSONParser(); 

        // getting JSON string from URL 
        JSONObject json = jParser.getJSONFromUrl(url); 

        try { 
         // Getting Array of Contacts 
         products = json.getJSONArray(TAG_PRODUCTS); 

         // looping through All Contacts 
         for(int i = products.length()-1; i >=0; i--){ 
          JSONObject c = products.getJSONObject(i); 

          // Storing each json item in variable 
          String cid = c.getString(TAG_CID); 
          String name = c.getString(TAG_NAME); 
          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 
          map.put(TAG_CID, cid); 
          map.put(TAG_NAME, name); 

          // adding HashList to ArrayList 
          contactList.add(map); 
          Log.d("value", contactList.toString()); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 


      } 
} 

請幫我在這。

回答

0

即使對於服務,您也無法在主線程上進行網絡訪問。你需要在Thread或AsyncTask中完成。

+0

如果它是標準的,那麼爲什麼它在三星和索尼。 – user2064667

+0

他們是3.0以前的設備嗎?有人建議你不要在2.3版本中完成,但直到3.0版本才能執行。在所有電話3.0+這是強制執行。 –

+0

我們可以在服務中運行AsyncTask嗎? – user2064667

0

問題: android.os.NetworkOnMainThreadException

原因: 長期運行的任務不應在主線程,否則用戶界面將被阻止運行。

解決方案: 嘗試onStartCommand()創建一個新的線程或使用Handler

看一看docs爲參考