【问题标题】:Android loopj + GCMIntentService sending message to a Handler on a dead threadAndroid loopj + GCMIntentService 在死线程上向 Handler 发送消息
【发布时间】:2013-12-27 10:02:08
【问题描述】:

我正在尝试在我的 android 应用程序中实现 GCMIntentService。

当我尝试在我的数据库中保存注册 ID 时,asynhttp 显示以下错误 " sending message to a Handler on a dead thread"

以下是我的代码

import com.google.android.gcm.GCMBaseIntentService;


public class GCMIntentService extends GCMBaseIntentService {
    ProgressBar progress;
    AlertDialog.Builder builder;
    AlertDialog dialog;
    Context context;

    Integer flags=0;
    String regId;

public GCMIntentService() {
    super(SENDER_ID);
}

private static final String TAG = "===GCMIntentService===";


@Override
protected void onRegistered(Context arg0, String registrationId) {
    Log.i(TAG, "Device registered at raj: regId = " + registrationId);
    tes(registrationId);
}

@Override
protected void onUnregistered(Context arg0, String arg1) {
    //Log.i(TAG, "unregistered = "+arg1);
}

@Override
protected void onMessage(Context arg0, Intent arg1) {
    Log.i(TAG, "new message= "+arg0);
    Bundle extras = arg1.getExtras();
    String tat=extras.getString("msg");
    JSONObject jsono = stringToJsonobj(tat.toString());
try {
    String message=jsono.getString("price");
    generateNotification(arg0, message);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


}

@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}


private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

public JSONObject stringToJsonobj(String result)
{
    JSONObject jObj = null;
        try {

        jObj = new JSONObject(result);          

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());

    }

     return jObj; 
}


private static void generateNotification(Context context, String message) {

    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher, message, when);
    String title = "Test Application";
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.putExtra("message", message);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults|= Notification.DEFAULT_LIGHTS;
    notification.defaults|= Notification.DEFAULT_VIBRATE;
    notification.flags |= Notification.DEFAULT_LIGHTS;
    notificationManager.notify(0, notification);


}


protected void tes(final String regId){
    ConnectionDetector cd= new ConnectionDetector(getApplicationContext());
    String domain = cd.getUrl();
    SharedPreferences mPrefs=getSharedPreferences("prefs",0);
    String token = mPrefs.getString("access_token", ""); 

    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams webparams = new RequestParams();
    webparams.put("fn", "loginProcess"); 
    webparams.put("email","username" ); 
    webparams.put("password", "password");

    client.post(domain, webparams, new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            Log.v("Start","Started-"+regId+"-User Id-"+regId);
        }

        @Override
        public void onSuccess(String response) {
            dialog.dismiss();
            Log.v("response",""+response);
            try {
                JSONObject obj = new JSONObject(response);
                Integer status=obj.getInt("result");
                String message=obj.getString("message");

                if(status==1){

                    // Success
                    Integer success=obj.getInt("success");
                    if(success==1){
                        Integer registered=obj.getInt("login");
                        if(registered==1){


                            /* Session Save */


                        }
                        else {

                        }

                    }

                    else {
                        //setEr("Something went wrong. Please try again.");

                    }
                }
                else {
                    //setEr("Something went wrong. Please try again.");

                }



            } catch (Throwable t) {

            }

        }

        @Override
        public void onFailure(Throwable e, String response) {
            //setEr("Something went wrong. Please try again."); 

            }
        });



    return;
}

有什么想法吗?请帮忙

提前致谢

【问题讨论】:

    标签: android web-services android-asynctask


    【解决方案1】:

    错误是因为您在 IntentService 中进行异步调用,请确保在 Intent 服务中使用同步调用,我遇到了同样的问题并通过同步解决了它。请参见下面 Loopj Lib 中的 Sync 调用示例。

    GCM 注册方法

    @Override
            protected void onRegistered(final Context context, final String registrationId)
            {
                final String userID = AIBSharedPreference.getInstance(context).getStringValue(StringConstants.PREF_USER_ID,
                        null);
                if (null != userID)
                {
                    WSUtils.registerGCMID(registrationId, userID);
                }
            }
    

    WS 调用保存注册 ID。

    public static void registerGCMID(final String regID, final String userID)
    {
        final RequestParams params = new RequestParams();
    
        params.put(WSConstant.PRM_USER_ID, userID);
        params.put(WSConstant.PRM_DEVICE_ID, regID);
    
        AppInBoxWS.syncPost("update_device_id", params);
    }
    

    WS 助手类“AppInBoxWS”

    public class AppInBoxWS
    {
        private static SyncHttpClient syncClient = new SyncHttpClient()
        {
    
            @Override
            public String onRequestFailed(final Throwable error, final String content)
            {
                return null;
            }
        };
    
        private static String getAbsoluteUrl(final String relativeUrl)
        {
            return WS_BASE_URL + relativeUrl;
        }
    
        public static String syncPost(final String url, final RequestParams params)
        {
            return syncClient.post(getAbsoluteUrl(url), params);
        }
    }
    

    【讨论】:

    • 我也在使用 AsyncHttpClient 而不是 SyncHttpClient 并将发送消息发送到死线程上的处理程序。非常感谢楼主
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2013-06-18
    • 1970-01-01
    • 2019-08-30
    • 2018-01-16
    • 1970-01-01
    • 2012-05-24
    相关资源
    最近更新 更多