为什么我的服务在Backgroung中不起作用?

如何解决为什么我的服务在Backgroung中不起作用?

我正在开发一个出租车应用程序,即使该应用程序在后台或屏幕关闭,该应用程序也需要保持跟踪驾驶员 我试图通过服务来执行此操作,但是它无法正常工作,而且我找不到问题所在

我的第二个问题是应用程序不上传某种图像,例如当我用手机拍摄高质量的照片并将其上传到服务器中时,应用程序一直说失败了,但是照片已上传到服务器上/而当我将屏幕截图取消上传后,效果很好

3Q /与出租车应用程序一起使用的服务器的最低要求是什么

这是MainActivity代码

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {



/** MAP **/
public static GoogleMap mMap;
public static Location currentLocation;

/** GOOGLE API CLIENT **/
private GoogleApiClient googleApiClient;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private LocationRequest locationRequest;
private static final long UPDATE_INTERVAL = 5000,FASTEST_INTERVAL = 5000; // = 5 seconds
private LocationManager locationManager;
private String provider;
public static String amount,id_ride,position,id_driver,note_,img,comment;

public static AlertDialog alertDialog;
private static TextView title;
private static final String HTTPS = "https://";
private static final String HTTP = "http://";

private static TextView ok,time;
private static ProgressBar progressBar2;
private static CountDownTimer countDownTimer = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = MainActivity.this;
    activity = this;
    connectionDetector=new ConnectionDetector(context);
    prefManager = new PrefManager(this);

    title = (TextView) findViewById(R.id.title);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Bundle objetbundle = this.getIntent().getExtras();
    String fragment_name = objetbundle.getString("fragment_name");

    if(!fragment_name.equals("")){
        notification = true;
        if(fragment_name.equals("ridenewrider"))
            selectItem(1);
        else if(fragment_name.equals("ridecompleted"))
            selectItem(4);
            /*else if(fragment_name.equals("ridecanceledrider"))
                selectItem(1);*/
    }

    balance = (TextView) findViewById(R.id.balance);
    user_photo = (CircleImageView) findViewById(R.id.user_photo);
    switch_statut = (SwitchCompat) findViewById(R.id.switch_statut);
    user_name = (TextView) findViewById(R.id.user_name);
    user_phone = (TextView) findViewById(R.id.user_phone);
    statut_conducteur = (TextView) findViewById(R.id.statut_conducteur);
    drawer_conducteur = (FrameLayout) findViewById(R.id.drawer_conducteur);
    drawer_user = (LinearLayout) findViewById(R.id.drawer_user);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this,mDrawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
    mDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationViewLeft = (NavigationView) findViewById(R.id.nav_view);
    mDrawerList = (RecyclerView) findViewById(R.id.rvdrawer);
    mDrawerList.setLayoutManager(new LinearLayoutManager(context));
    mDrawerList.setHasFixedSize(true);

    setDrawer();

    if (savedInstanceState == null) {
        if(fragment_name.equals(""))
            selectItem(0);
    }

    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
    }

    if(!isLocationEnabled(context))
        showMessageEnabledGPS();

    balance.setVisibility(View.GONE);
    if (M.getStatutConducteur(context).equals("yes")) {
        switch_statut.setChecked(true);
        statut_conducteur.setText("enabled");
    } else {
        switch_statut.setChecked(false);
        statut_conducteur.setText("disabled");
    }

    switch_statut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(switch_statut.isChecked()) {
                M.showLoadingDialog(context);
                new changerStatut().execute("yes");
            }else {
                M.showLoadingDialog(context);
                new changerStatut().execute("no");
            }
        }
    });

    if(!M.getPhoto(context).equals("")) {
        Glide.with(context).load(AppConst.Server_url + "images/app_user/" + M.getPhoto(context))
                .skipMemoryCache(false)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e,Object model,Target<Drawable> target,boolean isFirstResource) {
                        user_photo.setImageDrawable(getResources().getDrawable(R.drawable.user_profile));
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource,DataSource dataSource,boolean isFirstResource) {
                        return false;
                    }
                })
                .into(user_photo);
    }else{
        user_photo.setImageDrawable(getResources().getDrawable(R.drawable.user_profile));
    }

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria,false);
    if (provider != null) {
        currentLocation = locationManager.getLastKnownLocation(provider);
    }

    googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();

    updateFCM(M.getID(context));
}

public static void setTitle(String title_){
    title.setText(title_);
}

@Override
public void onDestroy() {
    stopService(new Intent(context,PayPalService.class));
    currentLocation = null;
    super.onDestroy();
}

/** Récupération user wallet**/
public class getWallet extends AsyncTask<String,Void,String> {
    @Override
    protected String doInBackground(String... params) {
        String url = AppConst.Server_url+"get_wallet.php";
        StringRequest jsonObjReq = new StringRequest(Request.Method.POST,url,new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            JSONObject msg = json.getJSONObject("msg");
                            String etat = msg.getString("etat");
                            if(etat.equals("1")){
                                balance.setText(M.getCurrency(context)+" "+msg.getString("amount"));
                            }else{

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {

            @Override
            protected Map<String,String> getParams() {
                Map<String,String> params = new HashMap<String,String>();
                params.put("id_user",M.getID(context));
                params.put("cat_user",M.getUserCategorie(context));
                return params;
            }

        };
        AppController.getInstance().addToRequestQueue(jsonObjReq);
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                10000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        if (this != null) {

        }

    }

    @Override
    protected void onPreExecute() {

    }
}

@Override
public void onLocationChanged(Location location) {
    this.currentLocation = location;

    if (currentLocation != null) {
        new setCurrentLocation().execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()));
    }
}

/** Update driver position  **/
private class setCurrentLocation extends AsyncTask<String,String> {
    @Override
    protected String doInBackground(String... params) {
        String url = AppConst.Server_url+"set_position.php";
        final String latitude = params[0];
        final String longitude = params[1];
        StringRequest jsonObjReq = new StringRequest(Request.Method.POST,new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {

                    }
                },M.getID(context));
                params.put("user_cat",M.getUserCategorie(context));
                params.put("latitude",latitude);
                params.put("longitude",longitude);
                return params;
            }

        };
        AppController.getInstance().addToRequestQueue(jsonObjReq);
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                10000,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        if (this != null) {

        }

    }

    @Override
    protected void onPreExecute() {

    }
}

/** Start COOGLE API Client **/
@Override
public void onStart() {
    super.onStart();

    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}

@Override
public void onStop() {
    super.onStop();

    if (googleApiClient != null) {
        googleApiClient.disconnect();
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            &&  ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    // Permissions ok,we get last location
    currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    startLocationUpdates();
}

private void startLocationUpdates() {
    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);

    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    }

    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}

/** Change driver status **/
private class changerStatut extends AsyncTask<String,String> {
    @Override
    protected String doInBackground(String... params) {
        String url = AppConst.Server_url+"change_statut.php";
        final String online = params[0];
        StringRequest jsonObjReq = new StringRequest(Request.Method.POST,new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        try {
                            M.hideLoadingDialog();
                            JSONObject json = new JSONObject(response);
                            JSONObject msg = json.getJSONObject("msg");
                            String etat = msg.getString("etat");
                            String online = msg.getString("online");
                            if(etat.equals("1")){
                                if(online.equals("yes")) {
                                    switch_statut.setChecked(true);
                                    statut_conducteur.setText("enabled");
                                    M.setStatutConducteur(online,context);
                                }else {
                                    switch_statut.setChecked(false);
                                    statut_conducteur.setText("disabled");
                                    M.setStatutConducteur(online,context);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                M.hideLoadingDialog();
                if(switch_statut.isChecked())
                    switch_statut.setChecked(false);
                else
                    switch_statut.setChecked(true);
            }
        }) {

            @Override
            protected Map<String,String>();
                params.put("id_driver",M.getID(context));
                params.put("online",online);
                return params;
            }

        };
        AppController.getInstance().addToRequestQueue(jsonObjReq);
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                10000,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        //to add spacing between cards
        if (this != null) {

        }

    }

    @Override
    protected void onPreExecute() {

    }
}

@Override
public void onRequestPermissionsResult(int requestCode,String permissions[],int[] grantResults) {
    switch (requestCode) {
        case LOCATION_REQUEST_CODE: {
            if(!isLocationEnabled(context))
                showMessageEnabledGPS();
            return;
        }

    }
}

public void showMessageEnabledGPSClient(){
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(context.getResources().getString(R.string.this_service_requires_the_activation_of_the_gps))
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface,int i) {
                    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No",int i) {
                    dialogInterface.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

public void showMessageEnabledGPS(){
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage("Activez le service GPS pour partager votre position avec les clients. Activez le GPS maintenant ?")
            .setCancelable(false)
            .setPositiveButton("Yes",int i) {
                    dialogInterface.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

private boolean isLocationEnabled(Context context){
    boolean enabled = false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        int mode = Settings.Secure.getInt(context.getContentResolver(),Settings.Secure.LOCATION_MODE,Settings.Secure.LOCATION_MODE_OFF);
        enabled = (mode != Settings.Secure.LOCATION_MODE_OFF);
    }else{
        LocationManager service = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        enabled =  service.isProviderEnabled(LocationManager.GPS_PROVIDER)||service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
    return enabled;
}

这就是服务

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MyService extends Service {

    private LocationRequest locationRequest;
    public static Location currentLocation;
    private GoogleApiClient googleApiClient;
    public static Context context;


    
    @Override

    public int onStartCommand(Intent intent,int flags,int startId) {
            if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    &&  ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}

            currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            startLocationUpdates();
        return START_STICKY;
    }

        private void startLocationUpdates() {
            locationRequest = new LocationRequest();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(5000);
            locationRequest.setFastestInterval(2000);

            if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            }

            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,(LocationListener) this);

        }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

解决方法

启动Android O的Android服务受到限制。经过一段时间的电池优化(在https://medium.com/oceanize-geeks/background-services-in-android-o-a38a7c624391https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c中进行了解释),Android OS会终止长时间运行的后台服务/进程。

相反,您可以使用Foreground service使应用程序在后台运行。前台服务要求连续显示通知,以便用户知道X应用程序正在后台执行某些工作。有关Foreground服务的实施,您可以参考https://codinginflow.com/tutorials/android/foreground-service

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-