首页 > 解决方案 > 一段时间后 StartForegroundService 停止工作

问题描述

我有一个由 awebView和一个组件组成的应用程序,该组件在应用程序运行时获取 DeviceID。

在我的MainActivity中,我调用startForegroundService(toastIntent);onCreate。

toastIntent是每 10 秒运行一次以检查通知的服务(通过查询数据库)

在我的toastIntent服务中,我调用t.schedule(doAsynchronousTask, 3000,10000);以便在应用程序运行后 3 秒运行它,然后每 10 秒检查一次通知(如果有通知显示应用程序通知用户)。

问题是,一段时间后,该服务停止并且我没有收到任何通知。出了什么问题?我是 AndroidStudio 的新手,我真的不明白是什么导致了这种行为。

是关于缓存限制吗?

编辑代码:

主要活动:

public class MainActivity extends AppCompatActivity {

    WebView web;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent toastIntent = new Intent(this, MyServices.class);
        startForegroundService(toastIntent);

        //TextView textDeviceID = findViewById(R.id.textImei);
        String android_id = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);

       //textDeviceID.setText(android_id);
        String base_url = "MY__URL";

        if(android_id != null) {
            base_url = base_url + "?device_id=" + android_id;
        }

        web = findViewById(R.id.webview);

        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSavePassword(true);

        web.loadUrl(base_url);

        web.setWebViewClient(new WebViewClient() {
                 @Override
                 public boolean shouldOverrideUrlLoading(WebView view, String url) {
                     // When user clicks a hyperlink, load in the existing WebView
                     if(url.contains("google")) {
                         Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                                 Uri.parse(url));
                         startActivity(intent);
                     }else {
                         web.loadUrl(url);
                     }
                     return true;
                 }
             }
            );

        }

    }

我的服务:

public class MyServices extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startService(new Intent(this,MyServices.class));
        Timer t = new Timer();
        final Handler handler = new Handler();


        // Timer task makes your service will repeat after every 20 Sec.
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {

                        //Do network call here

                        String deviceId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);

                        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                        String url = "REPLACED_FOR_PRIVACY" + deviceId;

                        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                new Response.Listener<String>() {

                                    @Override
                                    public void onResponse(String response) {
                                        JSONObject jsonResp = null;
                                        String areListe = null;
                                        try {
                                            jsonResp = new JSONObject(response);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        try {
                                            areListe = jsonResp.getString("areListe");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        if(areListe.equals("1")) {
                                            /**Creates an explicit intent for an Activity in app**/
                                            Intent resultIntent = new Intent(getApplicationContext() , MainActivity.class);
                                            resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                            PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(),
                                                    0 /* Request code */, resultIntent,
                                                    PendingIntent.FLAG_UPDATE_CURRENT);

                                            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
                                            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
                                            mBuilder.setContentTitle("New Notification")
                                                    .setContentText("Please open app")
                                                    .setAutoCancel(false)
                                                    .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                                                    .setContentIntent(resultPendingIntent);

                                            NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

                                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
                                            {
                                                int importance = NotificationManager.IMPORTANCE_HIGH;
                                                NotificationChannel notificationChannel = new NotificationChannel("1", "NOTIFICATION_CHANNEL_NAME", importance);
                                                notificationChannel.enableLights(true);
                                                notificationChannel.setLightColor(Color.RED);
                                                notificationChannel.enableVibration(true);
                                                notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                                                assert mNotificationManager != null;
                                                mBuilder.setChannelId("1");
                                                mNotificationManager.createNotificationChannel(notificationChannel);
                                            }
                                            assert mNotificationManager != null;
                                            mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
                                        }else {
                                            //pentru debug only
                                           // Toast.makeText(getApplicationContext(),"No Notifications" + areListe,Toast.LENGTH_SHORT).show();
                                        }

                                    }
                                }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //pentru debug only
                                    //Toast.makeText(getApplicationContext(),"Not working  :(",Toast.LENGTH_SHORT).show();
                                }
                        });

                        // Add the request to the RequestQueue.
                        queue.add(stringRequest);

                    }

                });
            }
        };
        //Starts after 20 sec and will repeat on every 20 sec of time interval.
        t.schedule(doAsynchronousTask, 3000,10000);  // 20 sec timer
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
    }
}

标签: javaandroid

解决方案


推荐阅读