-1

I'm working on an app where it needs to run the service to give regular update. But the problem is while testing the app in Micromax mobile it is giving error like follows.

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

The application runs perfectly on both samsung and sony. Async cannot be run inside service. Please give some suggestion for how to solve this problem.

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


            }
}

Please help me on this.

user2064667
  • 124
  • 1
  • 12

2 Answers2

0

You can't do network access on the main thread, even for a service. You need to do it in a Thread or AsyncTask.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

Issue: android.os.NetworkOnMainThreadException

Cause: Long running task should not run on Main thread otherwise UI will be blocked.

Solution: Try creating a new thread in onStartCommand() or use Handler

Have a look at docs for the reference

Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57