我正在开发一个需要运行服务才能定期更新的应用。但问题是在Micromax mobile中测试应用程序时会出现如下错误。
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 :(得分:0)
即使是服务,也无法在主线程上进行网络访问。您需要在Thread或AsyncTask中执行此操作。
答案 1 :(得分:0)
<强>问题:强> android.os.NetworkOnMainThreadException
<强>原因:强> 长时间运行的任务不应该在主线程上运行,否则UI将被阻止。
<强>解决方案:强>
尝试在onStartCommand()
中创建新主题或使用Handler
请参阅docs以获取参考资料