首页 > 解决方案 > 从后台刷应用程序并想调用 api

问题描述

我创建了一个 DeviceShutDownReceiver 接收器。

public class DeviceShutDownReceiver extends BroadcastReceiver {
    Context mContext;
    @Override
    public void onReceive(Context context, Intent intent)
    {
        mContext = context;

        //Make user offline when device is getting Shut down.
        new MakeUserOffline().execute();
    }

    private class MakeUserOffline extends AsyncTask<Void, Void, String> {
      //  ProgressDialog dialog = new ProgressDialog(Reg);
        //dialog.
      String result;
        @Override
        protected String doInBackground(Void... params) {
            Log.i("Check", "1()");
            String strUserId = BaseActivity.getUserId();
            int userId = Integer.parseInt(strUserId);
            final UserAvailabilityStatus obj = new UserAvailabilityStatus(userId,false);
            String webAddressToPost = Constants.BASE_URL + "DriverLocation/UpdateDriverOnlineStatus";
            try {
                Log.i("Check", "2()");
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(webAddressToPost);

                Gson gson = new GsonBuilder().create();
                String jsonStr = gson.toJson(obj);

                httpPost.addHeader("User-Agent", "Custom-Agent 1.0");
                httpPost.addHeader(Constants.AUTH_HEADER_KEY,Constants.AUTH_HEADER_VALUE);
                StringEntity se = new StringEntity(jsonStr);
                se.setContentType("application/json;charset=UTF-8");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json;charset=UTF-8"));
                httpPost.setEntity(se);

                HttpResponse response = httpClient.execute(httpPost);
                Log.i("Check", "3()");
                if (response.getStatusLine().getStatusCode() == 200) {
                    // Get the response string
                    InputStream inputStream = null;
                    inputStream = response.getEntity().getContent();
                    if (inputStream != null)
                        result = convertInputStreamToString(inputStream);
                    else
                        result = "Failure";

                    UserAvailabilityStatus responseId = gson.fromJson(
                            result, UserAvailabilityStatus.class);
                   // int responseId = fooFromJson.Id;
                    Log.i("Check", result);
                    if ((null == responseId)) {
                        //  Log.w(TAG, String.format("onLoadFinished() : But null value returned!"));
                        //Toast.makeText(mContext, "Status not updated", Toast.LENGTH_LONG).show();
                    }
                    else {
                        Log.i("Check", result);
                        if(responseId.getResult().equalsIgnoreCase("Success.")) {

                            //Toast.makeText(mContext, "Status updated successfully", Toast.LENGTH_SHORT).show();
                            saveAvailableStatusSharedPref(false);
                            Log.i("Check", responseId.getResult());
                        }
                        else{
                            //Toast.makeText(mContext, "Status could not be updated", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
            }

            return null;
        }
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
           // dialog.setMessage("Loading...");
           // dialog.show();
        }
        @Override
        protected void onPostExecute(String result) {
        }
    }

    private void saveAvailableStatusSharedPref(Boolean isAvailable){

        SharedPreferences sharedpreferences = mContext.getSharedPreferences(
                Constants.PREF_USER_AVAILABLE_STATUS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putBoolean(Constants.PREF_USER_AVAILABLE_STATUS, isAvailable);

        editor.commit();
    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;
    }
}

我从清单文件中调用这个接收器。

<receiver android:name=".DeviceShutDownReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            </intent-filter>
        </receiver>

当我从任务管理器刷应用程序时,我想调用一个 api,但是这个 api 没有调用。我想这个接收器没有打电话。

如果我遗漏了什么,请提出建议。

#######################################3

标签: androidreceiver

解决方案


如果我理解正确,您想webrequest在应用程序被终止时而不是在设备关闭时进行。

因此,您必须查看 Android Activity Lifecycle

来源:https ://developer.android.com/guide/components/activities/activity-lifecycle

将您的代码放在onStoporonDestroy中。无需自定义广播接收器。


推荐阅读