-1

我正在开发一个需要运行服务以提供定期更新的应用程序。但问题是在 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

该应用程序可以在三星和索尼上完美运行。异步不能在服务内部运行。请就如何解决这个问题提出一些建议。

更新服务.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();
                    }
            }
        }
    }
}

消息.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();
                    }


            }
}

请帮助我。

4

2 回答 2

0

您不能在主线程上进行网络访问,即使对于服务也是如此。您需要在 Thread 或 AsyncTask 中执行此操作。

于 2013-05-16T06:18:59.033 回答
0

问题: android.os.NetworkOnMainThreadException

原因: 长时间运行的任务不应在主线程上运行,否则 UI 将被阻塞。

解决方法: 尝试新建一个线程onStartCommand()或者使用Handler

查看文档以供参考

于 2013-05-16T06:31:07.013 回答