【问题标题】:application may be doing too much work on main thread even after using a different thread即使在使用不同的线程之后,应用程序也可能在主线程上做太多的工作
【发布时间】:2013-04-19 23:32:22
【问题描述】:

您好,我是 android 新手,正在关注一个 yamba 应用程序,该应用程序在 twitter 上发布和获取状态。在添加新部件之前,我工作正常。

我使用不同的线程来执行该帖子。但是一旦我运行该项目,logcat 会说“应用程序可能在主线程上做了太多的工作”。当我输入状态时,“线程退出并出现未捕获的异常”,由于这个 doInBackGround 方法中的 NullPointException。

任何人都可以帮助我吗?我什至注册了一个 Twitter 帐户以确保它不为空。但是非常感谢您的任何回答!

    public class MainActivity extends Activity implements OnClickListener,TextWatcher
    {
    private static final String TAG="StatusActivity";
    EditText editText;
    Button buttonUpdate;
    TextView textCount;
    private YambaApplication yamba;


//constructor
     @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

editText=(EditText) findViewById(R.id.editText);
buttonUpdate=(Button) findViewById(R.id.buttonUpdate);
textCount=(TextView) findViewById(R.id.textCount);
textCount.setText(Integer.toString(140));
textCount.setTextColor(Color.GREEN);

buttonUpdate.setOnClickListener(this);
editText.addTextChangedListener(this);
this.yamba=(YambaApplication)getApplication();
}   


    //Main task of posting, three method of AsyncTask
class PostToTwitter extends AsyncTask<String,Integer,String>
{
    @Override
    protected String doInBackground(String...statuses)
    {
        try{
             Twitter.Status status=yamba.getTwitter().updateStatus(statuses[0]);
             return status.text;
        }
        catch(TwitterException e){
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return "Failed to post";
        }
    }

在yamba应用java中有这个任务:

    public synchronized Twitter getTwitter(){
    if(twitter==null)
    {
        String username,password,APIroot;
        username=prefs.getString("username", "");
        password=prefs.getString("passord", "");
        APIroot=prefs.getString("APIroot", "http://yamba.marakana.com/api");

     if ( !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(APIroot) )
         {
            twitter= new Twitter(username,password);
             twitter.setAPIRootUrl(APIroot);
          }
     }
    return this.twitter;
  } 

【问题讨论】:

标签: android multithreading nullpointerexception


【解决方案1】:

不要在同时为 UI 服务的主循环中执行任何阻塞操作。在这种情况下,这包括向远程系统、twitter 和 yamba 发出请求。虽然它似乎已被移动到不同的线程,但您仍然在阻止 yamba 接口,同时在那里发出请求,这也会阻止它用于其他用途。

【讨论】:

  • 感谢您的回复。现在我再次查看 logcat,在创建主要活动之后,在我输入状态或进行任何动作之前,“应用程序可能正在主线程上做很多工作”。但是整个应用程序和主要活动的 onCreate() 只膨胀了 R 视图......这是否意味着同步任务是自动启动的?如果同步任务仍然会阻塞主线程,但我确实需要任务来报告,那么我应该使用什么来代替?格式有什么不清楚的地方?
  • 从一致缩进代码开始。什么是“logcat”?也就是说,也许你不应该逐字接收错误消息,即主线程超载,而不管它做什么都需要太长时间。这包括等待其他线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多