如何在Android进入暂停状态时发出服务器请求?

时间:2016-05-24 06:56:23

标签: android

我有一个名为otpverification的活动,它向服务器发送OTP生成请求。但是当活动进入暂停状态时,就像关闭应用程序时它在后台运行那种情况我想发送服务器请求。我怎么能这样做

2 个答案:

答案 0 :(得分:0)

对于此类操作,如果您使用服务会更好,请点击此链接" https://developer.android.com/training/run-background-service/create-service.html"或根据您的要求修改此示例

首先创建Service类并在清单文件中注册它

public class MyService extends Service {
 @Override
   public IBinder onBind(Intent arg0) {
  return null;
  }
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
  Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
  return START_STICKY;
}
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

从您的活动中调用此服务

public class MainActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  }


   @Override
   public void startService(View view) {
      startService(new Intent(getBaseContext(), MyService.class));
}
   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getBaseContext(), MyService.class));
}
}

注意 - 如果您想将任何数据从服务返回到您的活动,请使用广播接收器,请点击此处,例如https://github.com/commonsguy/cw-android/tree/master/Service/WeatherAPI

答案 1 :(得分:0)

我认为您必须使用异步Http客户端进行http请求。

相关问题