私はよく実行しているアプリケーションを作りました。友人リストとサーバーからのすべての表示)。問題は、アプリがバックグラウンド/ユーザーになっているときです。phonecall/userが別のアプリケーションを使用しています。自分のアプリケーションが接続を失ってしまい、ユーザーがサーバーからサービスを取得してしまいます(すべてのサービスはログイン中にユーザーIDに依存します)。私はこの問題を解決しようとしています。私のアプリはいつも大丈夫ですし、サーバーのアクティビティと対話しています。どのように私のネットワーク接続を作成し、FacebookやwhatsAppアプリのように動作するかを管理する方法。 画像を確認してください。最初はアプリが(プロフィール名と写真付きで)うまくやり取りしていて、もう1つはエラー(プロフィール名や写真なし)です。私は、アンドロイドのアプリケーションでサーバーとの連続的なやりとりに直面しています
私asyncTaskClass:
public class GetPostAsyncTaskWithInterface extends AsyncTask<String, Void, String> {
public AsyncResult asyncResult;
// HttpURLConnection httpURLConnection;
ProgressDialog progressDialog;
private final String baseUrl = UserInfo.getSiteUrl();
public Context context=null;
GetPostAsyncTaskWithInterface(Context context,AsyncResult asyncResult) {
this.context=context;
this.asyncResult= asyncResult;
}
@Override
protected void onPreExecute() {
//Toast.makeText(context,"Loading..",Toast.LENGTH_SHORT).show();
progressDialog=new ProgressDialog(context);
progressDialog.show();
}
@Override
protected String doInBackground(String... args) {
try {
// setting the URL
URL url = new URL(baseUrl+args[1]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// setting the method type
httpURLConnection.setRequestMethod(args[0]);
// httpURLConnection.setChunkedStreamingMode(0);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
Log.v("Url", args[2]);
// setting the identification key name with query params
bufferedWriter.write(args[2]);
bufferedWriter.flush();
bufferedWriter.close();
Log.v("GetPostA", url.toString());
httpURLConnection.setReadTimeout(10*1000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.connect();
int getPostStatus = httpURLConnection.getResponseCode();
Log.v("GetPostSts", String.valueOf(getPostStatus));
String line = "";
String res = "";
// if(getPostStatus == 200){
// prepare the output buffer
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
res += line;
}
inputStream.close();
// }
httpURLConnection.disconnect();
// Log.v("ResD", res.toString());
return res.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("GetPostCatchMal",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.v("GetPostCatchIOE", e.toString());
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(progressDialog.isShowing()){
try{
progressDialog.dismiss();
}catch (Exception e){
}
}
if(result!=null) {
asyncResult.asyncResult(result);
}
}
}
と私の活動のクラスは次のようである:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context = NavigationDrawerActivity.this;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View hView = navigationView.getHeaderView(0);
ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer);
ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer);
/****************************** own profile name and image show ************************** */
ownNameShow.setText(UserInfo.getOwnProfileName());
// new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100,100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria=new Criteria();
provider =lm.getBestProvider(criteria,false);
location = this.lm.getLastKnownLocation(provider);
this.locationListener = new NavigationDrawerActivity();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener);
if (location != null) {
setUpMapIfNeeded(location);
updateUserLatLong(location);
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).addApi(LocationServices.API).build();
//route
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// option menu.......................option menu,.,
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer_option_menu, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
setUpMapIfNeeded(location);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.v("DangerNotification","locN M"+location);
if (location != null) {
setUpMapIfNeeded(location);
UserInfo.setLat(location.getLatitude());
UserInfo.setLng(location.getLongitude());
UserInfo.setLocation(location);
}
//setUpMapIfNeeded(location);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(context, Live_MapActivity.class);
intent.putExtra("Driver", "anyFriend");
UserInfo.setFriendsId(friendIds.optString(marker.getId()));
startActivity(intent);
Toast.makeText(context, "You tracking " + marker.getTitle(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onLocationChanged(Location location) {
Log.v("DangerNotification", "locN " + location);
if (location != null && SharedPreference.getDefaults("ownUserId", context) != "0") {
updateUserLatLong(location);
//setUpMapIfNeeded(location);
float speed = location.getSpeed();
UserInfo.setSpeed(speed);
UserInfo.setLat(location.getLatitude());
UserInfo.setLng(location.getLongitude());
UserInfo.setLocation(location);
}
userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
12));
mMap.setMapType(UserInfo.getMapType());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
Toast.makeText(context, "Gps enabled", Toast.LENGTH_LONG).show();
}
}
@Override
public void onProviderDisabled(String provider) {
/* ********************************************* Gps checking ********************************************************** */
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled) {
Toast.makeText(context, "Gps Disable", Toast.LENGTH_LONG).show();
}
/* ************************************************************************************************************ */
}
private void setUpMapIfNeeded(Location location) {
//updateUserLatLong(location);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
LatLng userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
UserInfo.getZoomLevel()));
mMap.setMapType(UserInfo.getMapType());
userFriendsPos();
}
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
}
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Maps Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
location = LocationServices.FusedLocationApi.getLastLocation(
client);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void asyncResult(String result) {
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPostResume() {
super.onPostResume();
}
@Override
protected void onRestart() {
super.onRestart();
ownNameShow.setText(UserInfo.getOwnProfileName());
// new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100,100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);
if (location != null) {
setUpMapIfNeeded(location);
updateUserLatLong(location);
}
}
}
はあなたに感謝:)私は – AAA
Souhaib Guitouniをしようと、あなたがサービスへのコードの上に統合してくださいすることができます見ることができます。私はそうすることができないと私は推測する – AAA