2013-01-15 5 views
-2

안녕하세요 저는 Android 위젯을 만들려고합니다. 이 위젯에서 웹 서비스를 호출하고 텍스트를 가져 와서 특정 텍스트 간격으로 텍스트 뷰에서 데이터를 가져 와서 텍스트 뷰의 값을 업데이트하려고합니다. 예외가 발생했습니다. 여기 예외 발생 : android widget

Exception:java.lang.RuntimeException: Unable to start service [email protected]{cmp=com.example.newwidget 
/.UpdateService (has extras) }: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 

import android.appwidget.AppWidgetManager; 
    import android.appwidget.AppWidgetProvider; 
    import android.content.ComponentName; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.widget.RemoteViews; 
    import android.widget.RemoteViews.RemoteView; 
    import android.widget.Toast; 

    public class Widget extends AppWidgetProvider { 


@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, 
     int[] appWidgetIds) { 
    Toast.makeText(context, "OnUpdate", Toast.LENGTH_LONG).show(); 

     ComponentName thisWidget = new ComponentName(context, 
       Widget.class); 
      int[] allWidgetIds =  appWidgetManager.getAppWidgetIds(thisWidget); 
      Toast.makeText(context, "allWidgetIds", Toast.LENGTH_LONG).show(); 

      // Build the intent to call the service 
      Intent intent = new Intent(context.getApplicationContext(), 
       UpdateService.class); 
      Toast.makeText(context, "call UpdateService", Toast.LENGTH_LONG).show(); 

      intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds); 
      Toast.makeText(context, "", Toast.LENGTH_LONG).show(); 

      // Update the widgets via the service 
      context.startService(intent); 
} 

} 

UpdateService.java

import java.io.IOException; 

    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.ClientProtocolException; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.ResponseHandler; 
    import org.apache.http.client.methods.HttpGet; 
    import org.apache.http.impl.client.BasicResponseHandler; 
    import org.apache.http.impl.client.DefaultHttpClient; 

    import android.app.ProgressDialog; 
    import android.app.Service; 
    import android.appwidget.AppWidgetManager; 
    import android.content.ComponentName; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.os.IBinder; 
    import android.util.Log; 
    import android.widget.RemoteViews; 
    import android.widget.Toast; 

    public class UpdateWidget extends Service { 
    private RemoteViews views; 
    private String url; 
    private String strAPIRender; 
    private final HttpClient Client = new DefaultHttpClient(); 
    private String Content; 
    private String Error = null; 
    private ProgressDialog Dialog = new ProgressDialog(null); 
    private HttpResponse response; 
    private HttpEntity httpEntity; 


@Override 
    public void onStart(Intent intent, int startId) { 
     Log.d("AppWidget.UpdateService", "onStart()"); 
    Toast.makeText(UpdateWidget.this, "Onstart", Toast.LENGTH_LONG).show(); 
     // Build the widget update for today 
    Toast.makeText(UpdateWidget.this, "Updateviews", Toast.LENGTH_LONG).show(); 

     RemoteViews updateViews = buildUpdate(this); 
     Log.d("WordWidget.UpdateService", "update built"); 

Toast.makeText(UpdateWidget.this, "buildupdate finish", Toast.LENGTH_LONG).show(); 

     // Push update for this widget to the home screen 
    ComponentName thisWidget = new ComponentName(this, WidgetAppActivity.class); 

     AppWidgetManager manager = AppWidgetManager.getInstance(this); 

    Toast.makeText(UpdateWidget.this, "final update", Toast.LENGTH_LONG).show(); 
    manager.updateAppWidget(thisWidget, updateViews); 

    Log.d("WordWidget.UpdateService", "widget updated"); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    public RemoteViews buildUpdate(Context context) { 
     // Pick out month names from resources 
Toast.makeText(UpdateWidget.this, "buildupdate", Toast.LENGTH_LONG).show(); 
url = "http://www.webservicex.net/currencyconvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=INR"; 

     grabURL(url); 
Toast.makeText(UpdateWidget.this, "grabURL finish", Toast.LENGTH_LONG).show(); 

     String result = strAPIRender; 

views = new RemoteViews(context.getPackageName(), R.layout.activity_widget_app); 
     views.setTextViewText(R.id.update, result); 
     return views; 
    } 
    public void grabURL(String url) { 
Toast.makeText(UpdateWidget.this, "in grabURL method", Toast.LENGTH_LONG).show(); 



     Toast.makeText(null, "execute url", Toast.LENGTH_LONG).show(); 
     try { 
      HttpGet httpget = new HttpGet(url); 
    ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      Content = Client.execute(httpget, responseHandler); 
     } catch (ClientProtocolException e) { 
      Error = e.getMessage(); 
     //cancel(true); 
    } catch (IOException e) { 
      Error = e.getMessage(); 
      //cancel(true); 
     } 



     parseXml(Content); 
    } 



    public String parseXml(String content) { 
     try { 

      System.out.println(content); 
      try { 

       strAPIRender = XMLHandler.GetTagValue("double",content); 


      } catch (Exception e) { 
       System.out.println(" catch b"); 
      } 

     } catch (Exception e) { 
      System.out.println(" exception in parseXML"); 
     } 
     return strAPIRender; 


    } 


} 

매니페스트 파일

 <uses-sdk android:minSdkVersion="8" /> 
    <uses-permission android:name="android.permission.INTERNET"/> 

    <application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <receiver 
     android:name=".Widget" 
     android:icon="@drawable/ic_launcher" 
     android:label="A Widget" > 
     <intent-filter> 
      <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 
     </intent-filter> 

     <meta-data 
      android:name="android.appwidget.provider" 
      android:resource="@xml/widget_info" /> 
    </receiver> 
    <service android:name="com.example.newwidget.UpdateService"></service> 
    </application> 
,369 Widget.java 제가

시도 코드,

답변

0

는 UpdateService에서 다음 줄을 제거 :

private ProgressDialog Dialog = new ProgressDialog(null); 

는 "대화는"어디에서나 사용할 수 있도록 (그 클래스의 빠른 눈에) 나타나지 않습니다. 만약 당신이 그것을 사용하려고한다면 당신은 그것을 (실제로 컨텍스트가 필요하다) 그것을 인스턴스화 할 수 없다. 그게 당신이 요구하는 특정 오류를 해결해야합니다.

(비록이 오류를 수정하더라도이 코드가 예상대로 작동하는지 확신 할 수 없습니다. 디버그 목적으로 모든 토스트를 제거하고 로깅 및 logcat을 사용하거나, 또는 디버거를 사용하지 말고 네트워크 I/O (기본 방법으로 사용되는 기본 UI 스레드)를 사용하지 말고 (IntentService를 참조하십시오), 서비스에서 대화/경고/토스트를하지 마십시오. 대문자로 시작하는 멤버 변수와 같은 비표준 명명 규칙에주의하십시오 (규칙을 준수하지 않아도 일관성이없는 경우 특히 그렇습니다).

+0

도움을 주셔서 감사합니다. .i 내 코드를 개선하려고합니다. –