Android 从后台滑动应用程序并希望调用api
我已经创建了一个DeviceShutDownReceiver接收器Android 从后台滑动应用程序并希望调用api,android,receiver,Android,Receiver,我已经创建了一个DeviceShutDownReceiver接收器 public class DeviceShutDownReceiver extends BroadcastReceiver { Context mContext; @Override public void onReceive(Context context, Intent intent) { mContext = context; //Make user off
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;
}
}
公共类设备ShutdownReceiver扩展了BroadcastReceiver{
语境;
@凌驾
公共void onReceive(上下文、意图)
{
mContext=上下文;
//在设备关闭时使用户脱机。
新建MakeUserOffline().execute();
}
私有类MakeUserOffline扩展异步任务{
//ProgressDialog=新建ProgressDialog(Reg);
//对话。
字符串结果;
@凌驾
受保护字符串doInBackground(无效…参数){
Log.i(“检查”,“1()”);
字符串strUserId=BaseActivity.getUserId();
int userId=Integer.parseInt(strUserId);
final UserAvailabilityStatus obj=新的UserAvailabilityStatus(userId,false);
字符串webAddressToPost=Constants.BASE_URL+“DriverLocation/UpdateDriverOnlineStatus”;
试一试{
Log.i(“检查”,“2()”);
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(webAddressToPost);
Gson Gson=new GsonBuilder().create();
字符串jsonStr=gson.toJson(obj);
addHeader(“用户代理”、“自定义代理1.0”);
httpPost.addHeader(常数.AUTH\u头\u键,常数.AUTH\u头\u值);
StringEntity se=新的StringEntity(jsonStr);
setContentType(“application/json;charset=UTF-8”);
se.setContentEncoding(新的BasicHeader(HTTP.CONTENT\u类型,
“application/json;charset=UTF-8”);
httpPost.setEntity(se);
HttpResponse response=httpClient.execute(httpPost);
Log.i(“检查”,“3()”);
if(response.getStatusLine().getStatusCode()==200){
//获取响应字符串
InputStream InputStream=null;
inputStream=response.getEntity().getContent();
如果(inputStream!=null)
结果=convertInputStreamToString(inputStream);
其他的
结果=“失败”;
UserAvailabilityStatus responseId=gson.fromJson(
结果,UserAvailabilityStatus.class);
//int responseId=fooFromJson.Id;
Log.i(“检查”,结果);
if((null==responseId)){
//Log.w(TAG,String.format(“onLoadFinished():但返回空值!”);
//Toast.makeText(mContext,“状态未更新”,Toast.LENGTH_LONG.show();
}
否则{
Log.i(“检查”,结果);
if(responseId.getResult().equalsIgnoreCase(“Success”)){
//Toast.makeText(mContext,“状态更新成功”,Toast.LENGTH_SHORT.show();
SaveAvailableStatusSharedRef(false);
Log.i(“Check”,responseId.getResult());
}
否则{
//Toast.makeText(mContext,“状态无法更新”,Toast.LENGTH_SHORT.show();
}
}
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(例外e){
}
返回null;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//setMessage(“加载…”);
//dialog.show();
}
@凌驾
受保护的void onPostExecute(字符串结果){
}
}
私有void saveAvailableStatusSharedRef(布尔值isAvailable){
SharedReferences SharedReferences=mContext.getSharedReferences(
Constants.PREF\u USER\u AVAILABLE\u STATUS,Context.MODE\u PRIVATE);
SharedReferences.Editor=SharedReferences.edit();
editor.putBoolean(Constants.PREF_USER_AVAILABLE_STATUS,isAvailable);
commit();
}
私有静态字符串convertInputStreamToString(InputStream InputStream)
抛出IOException{
BufferedReader BufferedReader=新的BufferedReader(
新的InputStreamReader(inputStream));
字符串行=”;
字符串结果=”;
而((line=bufferedReader.readLine())!=null)
结果+=行;
inputStream.close();
返回结果;
}
}
我正在从清单文件给这个接收者打电话
<receiver android:name=".DeviceShutDownReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>
当我从任务管理器滑动应用程序时,我想调用一个api,但该api没有调用。我想是的,这个接线员没有打电话
如果我遗漏了什么,请提出建议
#######################################3如果我理解正确,您希望在应用程序关闭时而不是在设备关闭时发出
webrequest
因此,您必须了解Android活动生命周期
资料来源:
将代码放在顶部的或存储区中。无需定制广播接收器。阅读文档: