gpt4 book ai didi

android - 如何在 Android 的服务中使用 AsyncTask?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:41 25 4
gpt4 key购买 nike

我正在尝试在它给出异常的代码下面运行:

 java.lang.RuntimeException: Unable to start service com.example.testfeeds.UpdateWidgetService@410a33c8 with Intent {  cmp=com.example.testfeeds/.UpdateWidgetService (has extras) }: android.os.NetworkOnMainThreadException

据我所知,新版本的 Android 不允许在主线程中进行网络操作。人们建议我使用异步任务但我不知道如何使用它。有人可以用下面的代码告诉我吗?

提前致谢

public class WidgetService extends Service {
/*
* So pretty simple just defining the Adapter of the listview
* here Adapter is ListProvider
* */

/*@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
int appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);

return (new ListProvider(this.getApplicationContext(), intent));
}*/

public static int numberOfItems=0;
//numberOfItems=0;
private static String LOG = "testwidgets";
ArrayList<String> feedsPubDate;
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
Log.i(LOG, "Called");
// Create some random data
feedsPubDate=new ArrayList<String>();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this .getApplicationContext());
int[] allWidgetIds = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
ComponentName thisWidget = new ComponentName(getApplicationContext(), WidgetProvider.class);
int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
Log.w(LOG, "From Intent" + String.valueOf(allWidgetIds.length));
Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));
for (int widgetId : allWidgetIds) {
// Create some random data
///////////////////////////////////////////////////////////////////////////

RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(),
R.layout.widget_layout);
Log.d("numberOfItems intially", String.valueOf(numberOfItems));
try {
numberOfItems=doTestFeed();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Set the text
remoteViews.setTextColor(R.id.empty_view,Color.WHITE);
remoteViews.setTextViewText(R.id.empty_view," "+ String.valueOf(numberOfItems));
Log.w(LOG, String.valueOf(numberOfItems));
////////////////////////////////////////////////////////////////////////////

// Register an onClickListener
Intent clickIntent = new Intent(this.getApplicationContext(),
WidgetProvider.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
allWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.empty_view, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
stopSelf();
super.onStart(intent, startId);

}



@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}


int doTestFeed() throws MalformedURLException, ParseException
{
Log.d("msg"," in do test feed");
InputStream is = null;
int x = 0;
URL myURL = new URL("http://yunn.yu.edu.jo/index.php?option=com_content&view=category&id=55&layout=blog&Itemid=104&format=feed&type=rss");
try {
URLConnection conn = myURL.openConnection();
is = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
Log.d("msg","before making parsing");
x=parseXML(parser);
Log.d("msg","after making parsing");
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("msg"," done testing");
return x;
}
//////////////////////////////////////////////////////////////////////////////////
@SuppressLint("SimpleDateFormat")
private int parseXML(XmlPullParser parser) throws XmlPullParserException,IOException, ParseException
{
Log.d("msg"," in parser");
int eventType = parser.getEventType();
int getElement=0;
String pubDate=null;
while (eventType != XmlPullParser.END_DOCUMENT){
String tagName = null;
switch (eventType){
//----------------------------------//
case XmlPullParser.START_DOCUMENT:
{
// do nothing
}
break;
//----------------------------------//
case XmlPullParser.START_TAG:
{ tagName = parser.getName();
if ("item".equals(tagName)){
getElement=1;
} else if (getElement!=0){
if ("pubDate".equals(tagName)){
pubDate= parser.nextText();
feedsPubDate.add(pubDate);
Log.d("value",pubDate);
}
}
}
break;
//----------------------------------//
case XmlPullParser.END_TAG:
{ tagName = parser.getName();
if (tagName.equalsIgnoreCase("item") && getElement != 0){
}
}
break;
//----------------------------------//
}// end-switch.
eventType= parser.next();
}// end-while.
int i=0;
SharedPreferences sp = getSharedPreferences("tempData", 0);
String dateStringA=sp.getString("recentPubDate", null);
Log.d("oldest date",dateStringA);
for(String s : feedsPubDate )
{
String dateStringB = feedsPubDate.get(i);
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
Date dateA = null;
try {
dateA = parserSDF.parse(dateStringA);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date dateB = null;
try {
dateB = parserSDF.parse(dateStringB);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dateA.compareTo(dateB) < 0) {
Log.d("imp msg","one new item");
numberOfItems++;
}
i++;
}
Log.d("update result", String.valueOf(numberOfItems));
// Toast.makeText(GeneralNews.this,"The size of the list"+feedsTitles.size() , Toast.LENGTH_LONG).show();
return numberOfItems;
} //end xmlParser method.
//////////////////////////////////////////////////////////////////////////////////
}

最佳答案

我认为这个问题可能对您有帮助: How to use AsyncTask

您可以使您的 AsyncTask 成为服务的内部类,并在 AsyncTask 的 doInBackground() 方法中执行您的网络操作。从 doInBackground() 您可以返回任何类型的数据 到 AsyncTask 的 onPostExecute() 方法,在这里您可以对接收到的数据做进一步的处理数据。

这里是一个 AsyncTask 示例: AsyncTask Android example

关于android - 如何在 Android 的服务中使用 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com