Android 后台服务在滑出时崩溃

2023-12-14

当我从任务管理器中删除我的应用程序时。剩下 0 个进程和 1 个服务。应用程序一次又一次崩溃,我应该做什么来解决它?这是我的服务等级。我还想问一件事OnStart()方法和OnStartCommand()方法之间的区别?

package com.example.vaccinationsystem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.TabHost.OnTabChangeListener;

@SuppressLint("Override")
public class BackgroundServices extends Service {

String userId;
SoapObject request;
PropertyInfo p_userId;
SoapSerializationEnvelope envelope;
HttpTransportSE httpTransport;
SoapPrimitive response;
ArrayList<String> listRec;
String s;
int totalDifference;
int countNotification = 0;

private static final String METHOD_NAME = "Alerts";
private static final String NAMESPACE = "http://org.fyp.ws";
private static final String SOAP_ACTION = "http://org.fyp.ws/Alerts";
private static final String URL = StaticIP.ipAddress
        + "GeneralUserServices?wsdl";

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

// @Override
// public void onCreate() {
//
// Toast.makeText(this, "Congrats! MyService Created",
// Toast.LENGTH_LONG).show();
// // Log.d(TAG, "onCreate");
// }

@Override
public void onStart(Intent intent, int startId) {


    userId = intent.getExtras().getString("user_Id");
    listRec = new ArrayList<String>();
    request = new SoapObject(NAMESPACE, METHOD_NAME);
    p_userId = new PropertyInfo();
    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    httpTransport = new HttpTransportSE(URL);

    p_userId.setName("userId");// Define the variable name in the web
    p_userId.setValue(userId);// Define value for fname variable
    p_userId.setType(String.class);// Define the type of the variable
    request.addProperty(p_userId);// Pass properties to the variable

    envelope.setOutputSoapObject(request);


    try {

        httpTransport.call(SOAP_ACTION, envelope);
        response = (SoapPrimitive) envelope.getResponse();
        // Toast.makeText(getApplicationContext(), response.toString(),
        // Toast.LENGTH_LONG).show();

        String[] row = response.toString().split("`");

        for (int i = 0; i < row.length; i++) {

            String[] record = row[i].split("~");
            // totalDifference = 0;
            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            String curDate = df.format(c.getTime()).toString();
            String visitDate = record[1];

            java.util.Date cD = df.parse(curDate);
            java.util.Date vD = df.parse(visitDate);

            Calendar cCurDate = Calendar.getInstance();
            cCurDate.setTime(cD);
            cCurDate.add(Calendar.DAY_OF_YEAR, 0);
            java.util.Date newCurDate = cCurDate.getTime();

            Calendar cNotificationStartVisitDate = Calendar.getInstance();
            cNotificationStartVisitDate.setTime(vD);
            cNotificationStartVisitDate.add(Calendar.DAY_OF_YEAR, -15);
            java.util.Date notificationStartDate = cNotificationStartVisitDate
                    .getTime();

            Calendar cOrignalVisitDate = Calendar.getInstance();
            cOrignalVisitDate.setTime(vD);
            cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, 0);
            java.util.Date newOriDateVisitDate = cOrignalVisitDate
                    .getTime();
            totalDifference = 0;

            if (notificationStartDate.before(newCurDate)) {

                while (newOriDateVisitDate.after(newCurDate)) {
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, -1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference++;
                    s = "left";
                }
                while (newOriDateVisitDate.before(newCurDate)) {
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR, +1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference++;
                    s = "ago";
                }
                countNotification++;
                listRec.add(record[2] + " Vaccine due: " + String.valueOf(totalDifference)
                        + " days " + s);

            }

        }

        for (int j = 0; j < countNotification; j++) {

            NotificationManager nm = (NotificationManager) getApplicationContext()
                    .getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
            Notification note = new Notification(R.drawable.nav_down,
                    "Vaccination ALerts!", System.currentTimeMillis());
            Intent inNotification = new Intent(this,GenUserFunction.class);
            inNotification.putExtra("user_id", userId);
            PendingIntent i =  PendingIntent.getActivity(getBaseContext(), 0,inNotification, 0);
            note.setLatestEventInfo(getApplicationContext(), "Vaccine       Due",
                    listRec.get(j), i);
            nm.notify(j, note);


        }



        // Toast.makeText(getApplicationContext(),
        // String.valueOf(listRec.size()), Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        // TODO: handle exception
        System.out.println(e.getMessage());

    }




    // Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

    // Note: You can start a new thread and use it for long background
    // processing from here.
}





@Override
public void onDestroy() {


enter code here
    super.onDestroy();

    // Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
    // Log.d(TAG, "onDestroy");
}
   }

  1. void onStart(Intent intent, int startId)已弃用,您需要使用int onStartCommand(Intent intent, int flags, int startId)反而。
  2. onStart(...)被称为来自onStartCommand(...)为了向后兼容,以及默认实现onStartCommand(...)返回 START_STICKY 值。所以,杀掉之后,你的服务会被系统重新启动。当系统重新启动该服务时,onStart(...)可以使用空意图对象调用方法,并且intent.getExtras().getString("user_Id")抛出NullPointerException,服务就会崩溃,并被系统重新启动...

结论:您需要检查intent对象为null在使用它之前。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 后台服务在滑出时崩溃 的相关文章

  • 如何使用 android:layout 属性实例化自定义首选项的布局

    我可以通过以下方式设置适当的布局以供偏好android layout属性 举个例子
  • 将JSON数据解析到Android ListView中

    我已经潜伏这个网站很长一段时间了 幸运的是 到目前为止我所有的问题都得到了解答 我希望你们中的一些人能够阐明我的问题 我可以成功地让 ListView 来显示字符串数组 但是当我尝试将 JSON 数据解析为数组时 我的程序只是强制关闭 而
  • ViewFlipper中的VideoView在播放视频时是透明的

    我有一个 Activity 在 ViewFlipper 中设置了两个视图 其中一个视图是带有 GLSurfaceView 和一些其他小部件的布局 另一个视图只有带有 TextView 和 VideoView 的布局 当我单击 GLSurfa
  • Facebook4j API:搜索

    我正在使用 Facebook4j 通过关键字获取状态 facebook4j conf ConfigurationBuilder fac new facebook4j conf ConfigurationBuilder fac setDebu
  • AltBeacon 服务位于单独的 Android 进程中

    我需要帮助 有一个适用于 Xamarin Android 的应用程序 在其中 启动了一个与 AltBeacon 库配合使用的服务 在此服务中 创建了一个线程 在该线程中不断扫描信标 服务以 StartForeground 启动 该服务应该有
  • 如何在其他呼叫运行时以编程方式合并呼叫(电话会议)

    我的要求是这样的 假设我当时正在拨打一个号码 并且我想以编程方式拨打另一个号码 到目前为止 我所做的是 当某些呼叫已经进行时 我能够呼叫特定号码 例如 假设我正在拨打号码 123 1 分钟后 通过使用Alarm Manger我触发一个事件来
  • Android Studio 安装失败,APK 未签名

    最近从 Eclipse 更改为 Android Studio 我还更改了 JDKjava open jdk to jdk1 7 0 45 现在我尝试运行我的第一个应用程序 并收到以下消息 Installation failed since
  • org.apache.http.conn.HttpHostConnectException:在 android 中连接到 http://localhost 被拒绝

    我正在制作一个应用程序 在执行它时将图像上传到服务器并将其数据库更新到android中的服务器 它显示错误 Connection to http localhost refused 还有更多错误 我研究了这个问题 发现不是提供 URL 连接
  • 在没有 BluetoothManagerCallback 的情况下调用 getBluetoothService

    我正进入 状态getBluetoothService called with no BluetoothManagerCallback在我的 Android 应用程序中经常出现错误 我不知道是什么原因导致这个或任何有关蓝牙管理器回调的事情 谁
  • 如何在 Android Studio 中构建项目测试目录?

    目前还没有这方面的约定 但是现在我如何构建 Android Studio 的测试目录呢 Android 测试基础 http developer android com tools testing testing android html页面
  • Android WebView文件上传

    我正在开发一个 Android 应用程序 基本上它是一个WebView和一个进度条 Facebook 的移动网站 m facebook com 已加载到WebView 当我单击 选择文件 按钮上传图像时 没有任何反应 我已经尝试了所有的解决
  • java.net.ProtocolException:流意外结束

    我面临一个奇怪的问题 并且无法调试它 我已经实现了上传数据流的逻辑 并使用 Volley 来实现相同的功能 我在HurlStack addBodyIfExistsapi 以便可以处理 application octet stream 类型的
  • 运行 Android 应用程序时出现错误

    我已经使用 Eclipse 创建了一个 Android 应用程序 但应用程序未在 AVD 上运行 它显示 不幸的是已停止工作 日志猫消息如下 07 29 04 59 50 789 W dalvikvm 784 threadid 1 thre
  • 推特更新状态

    我正在通过 twitter4j 将 Twitter 集成到 Android 我可以成功阅读我发布的推文 现在我试图用它发布推文 但我不能 我收到如下奇怪的警告 02 01 16 28 43 298 WARN System err 729 4
  • 通知操作而不启动新活动?

    我计划提供一个包含两个操作的提醒通知 一个用于批准登录请求 一个用于拒绝登录请求 通过单击这些操作中的任何一个 我希望向我的服务器发出 HTTP 请求 最重要的是 我不想启动新的 Activity 或根本不想将用户重定向到我的应用程序 Co
  • 如何向开关对象添加/更改波纹效果

    下面是我自定义的开关 红圈是默认的波纹效果 我发现设置一个波纹可绘制作为开关的背景 控制波纹的颜色
  • Android Jetpack Compose 尺寸随持续时间变化的动画

    如何在 Jetpack Compose 中添加内容大小更改动画的持续时间 尝试使用Modifier animateContentSize 并通过动画规格具有持续时间 但它只是突然进入或退出 没有观察到持续时间 Column Modifier
  • android 中的 java.net.URL ..新手问题

    我是java新手 正在尝试android开发 以下代码生成 malformedURLException 有人可以帮助我识别异常吗 任何提示都会非常有帮助 package com example helloandroid import and
  • 如何解决android程序中的警告“从不本地读取”

    为什么我收到警告说 The field testscreen ScaleAnimToShow mVanishAfter is never read locally testscreen java testscreen src com tes
  • Android Studio 中自动打开“运行设备”选项卡

    在 Android Studio Flamingo 中有一个名为跑步设备并且它会在每次之后自动打开运行应用程序 有办法禁止这个自动打开吗 我尝试禁用启用物理 Android 设备的镜像选项 但选项卡仍然自动打开 基于此issue https

随机推荐