2016-03-26 162 views
0

我有一個service是通過String of JsonMainActivityAndroid - 接收廣播意圖錯誤?

GetSubjects.class:

public class GetSubjects extends Service { 
    String URL = "http://webservice.jim.com/YYY/XXXX.asmx"; 
    String Webresponse = "IS NULL ?"; 
    int scode = 1597536485; 
    String result; 
    public final static String MY_ACTION = "MY_ACTION"; 
    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(final Intent intent, int flags, final int startId) { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       handleStart(intent, startId); 
      } 
     }; 
     Thread t = new Thread(r); 
     t.start(); 
     return START_NOT_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
    } 

    void handleStart(Intent intent, int startId) { 
     try { 
      Params_GetSubjects param = new Params_GetSubjects(scode); 
      result = new mGetSubjects().execute(param).get(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } 
    } 

    public class mGetSubjects extends AsyncTask<Params_GetSubjects, String, String> { 

     String NAMESPACE = "http://tempuri.org/"; 
     String METHOD_NAME = "Get"; 
     String SOAP_ACTION = "http://tempuri.org/Get"; 
     @Override 
     protected String doInBackground(Params_GetSubjects... params) { 
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      request.addProperty("scode", params[0].Scode); 
      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.dotNet = true; 
      envelope.setOutputSoapObject(request); 
      HttpTransportSE conn = new HttpTransportSE(URL); 
      Object object; 
      try { 
       conn.call(SOAP_ACTION, envelope); 
       //SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 
       object = envelope.getResponse(); 
       Webresponse = object.toString(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
       return "NULL"; 
      }finally { 
       ThreadFinish threadfinish = new ThreadFinish(); 
       threadfinish.start(); 
       return Webresponse; 
      } 
     } 
    } 
    public class ThreadFinish extends Thread{ 

     @Override 
     public void run() { 
      try { 
       Intent intent = new Intent(); 
       intent.setAction(MY_ACTION); 
       intent.putExtra("DATAPASSED", result); 
       sendBroadcast(intent); 
      }catch (Exception e){ 
       e.printStackTrace(); 
      }finally { 
       stopSelf(); 
      } 
     } 
    } 
} 

這裏是我的MainActivity:

public class MainActivity extends AppCompatActivity { 
    MyReceiver myReceiver; 
    private RecyclerView.LayoutManager layoutManager; 
    private DrawerAdapter mDrawerAdapter; 
    private RecyclerView mRecyclerView; 
    List<DrawerItem> draweritemList; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     startService(new Intent(MainActivity.this, GetSubjects.class)); 

    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     switch (id) { 
      case android.R.id.home: 
       mDrawerLayout.openDrawer(GravityCompat.START); 
       return true; 
      case R.id.action_settings: 
       return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    protected void onStart() { 
     myReceiver = new MyReceiver(); 
     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(GetSubjects.MY_ACTION); 
     registerReceiver(myReceiver, intentFilter); 
     super.onStart(); 
    } 

    @Override 
    protected void onStop() { 
     this.unregisterReceiver(myReceiver); 
     super.onStop(); 
    } 

    private class MyReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 

       String datapassed = arg1.getExtras().getString("DATAPASSED"); 
       Log.i("ASDQWRRYGH",datapassed); 

       draweritemList = JsonParser.parseFeed(datapassed); 

       for (int i=0;i < draweritemList.size();i++) 
       { 
        Log.i("ASDQWRRYGH",draweritemList.get(i).getTitle()); 
       } 



     } 

    } 
} 

這裏是我的JsonParer:

public class JsonParser { 
    public static List<DrawerItem> parseFeed(String content) { 
     try { 
      JSONObject jsonRootObject = new JSONObject(content); 
      JSONArray jsonArray = jsonRootObject.optJSONArray("Rows"); 
      List<DrawerItem> draweritemList = new ArrayList<>(); 
      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONObject obj = jsonArray.getJSONObject(i); 
       DrawerItem draweritem = new DrawerItem(); 

       draweritem.setId(obj.getString("Id")); 
       draweritem.setTitle(obj.getString("Title")); 
       draweritemList.add(draweritem); 
      } 
      return draweritemList; 
     } catch (JSONException e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 
} 

常常讓我從服務結果卻常常讓我怒吼錯誤,我能做些什麼?:

enter image description here

+0

你正在讓你的線程全部糾結,並且你最終在'result'被設置之前進行廣播。你並不需要'ThreadFinish'類。最簡單的解決方法是將廣播移到'result = ...'行後面。不過,真的,你可以/應該把所有東西放在一個單獨的線程中;無論是在'AsyncTask'還是'Thread'執行你的'Runnable'。 –

+1

非常非常感謝,我的問題與您的幫助解決。插入您的投票響應。謝謝很多。 –

回答

1

你必須在執行三個額外的線程您Service; AsyncTask和兩個Thread s。第一個Thread正在執行您的AsyncTask,但由於您在其上調用get()將其返回值分配給returnString,因此它被阻止。當網絡交易在AsyncTask中完成時,它會啓動另一個Thread發送廣播,並且這種情況發生在doInBackground()可以返回以設置returnString的值之前,最終在廣播仍然爲空時結束。

最簡單的解決方法是將廣播移動到result = ...行之後,並擺脫ThreadFinish類。

儘管如此,在單個線程中依次執行所有操作可能更好一些;請在AsyncTaskThread執行Runnable