【问题标题】:Network call inside a Service for a widget小部件的服务内的网络调用
【发布时间】:2013-10-23 09:33:16
【问题描述】:

我有一个与 Android Widget 相关的问题(主屏幕上的那些) 我正在尝试创建一个会定期更新其内容的小部件。

我使用一个被调用的服务来做到这一点。 当我尝试在此服务中进行基本网络调用 (GET) 时,我遇到了 NetworkOnMainThread 异常。

我知道这个异常是什么,但我认为 Android 中的服务位于单独的线程中。所以我只是误会了......

所以,为了做到这一点,我做了一个 AsyncTask 但我对我的代码不满意,我只是觉得我做的不是一个好的用法。 打电话给任何人告诉我我的想法是否正确?

这是我的服务内容:

public class ServiceUpdate extends Service
{
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    new AsyncTask<Void, Void, Void>()
    {
        String res = null;

        @Override
        protected Void doInBackground(Void... params)
        {
            // Getting something from the WWW
            res = Network.getStringFromWS("http://wordpress.org/plugins/about/readme.txt");
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            // Substring for test
            res = res.substring(0, 100);

            RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.widget_layout);
            remoteViews.setTextViewText(R.id.tvTime, res);

            ComponentName thiswidget = new ComponentName(getApplicationContext(), TimeWidgetProvider.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());
            manager.updateAppWidget(thiswidget, remoteViews);

            super.onPostExecute(result);
        }
    }.execute();

    return super.onStartCommand(intent, flags, startId);
}

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

}

谢谢大家的观点!

【问题讨论】:

    标签: android service android-asynctask


    【解决方案1】:

    不要在服务中使用AsyncTask,而是扩展IntentService,这样更简单。

    另外,最好有某种缓存机制。首先更新缓存,然后使用缓存中的数据更新小部件。这样,您的小部件将完全自主。您可以为此使用内容提供程序。

    还有一个注意事项。使用简单服务时,不要忘记停止它。在您的情况下,您必须在onPostExecute 中致电stopSelf。您不必明确停止 IntentService

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多