Android的后台服务崩溃,它刷出来 [英] Android background Service crash while It swipe out

查看:252
本文介绍了Android的后台服务崩溃,它刷出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我删除我的应用程序从任务manager.0流程和1个服务离开了。应用程序也再次崩溃又一次我应该怎么做才能解决这个问题?这是我的服务类。我想问一件事的OnStart()方法和OnStartCommand()方法?的区别

 包com.example.vaccinationsystem;

进口java.text.SimpleDateFormat的;
进口的java.util.ArrayList;
进口的java.util.Calendar;

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

进口android.annotation.Sup pressLint;
进口android.app.AlarmManager;
进口android.app.Notification;
进口android.app.NotificationManager;
进口android.app.PendingIntent;
进口android.app.Service;
进口android.content.Intent;
进口android.os.IBinder;
进口android.os.SystemClock;
进口android.util.Log;
进口android.widget.TabHost.OnTabChangeListener;

@燮pressLint(覆盖)
公共类BackgroundServices延伸服务{

字符串userid;
SoapObject请求;
的PropertyInfo p_userId;
SoapSerializationEnvelope信封;
HttpTransportSE httpTransport;
SoapPrimitive响应;
ArrayList的<字符串> listRec;
字符串s;
INT totalDifference;
INT countNotification = 0;

私有静态最后弦乐METHOD_NAME =警报;
私有静态最后弦乐NAMESPACE =htt​​p://org.fyp.ws;
私有静态最后弦乐SOAP_ACTION =htt​​p://org.fyp.ws/Alerts;
私有静态最后字符串URL = StaticIP.ipAddress
        +GeneralUserServices WSDL?;

@覆盖
公众的IBinder onBind(意向为arg0){
    返回null;
}

// @覆盖
//公共无效的onCreate(){
//
// Toast.makeText(这一点,恭喜!为MyService创建,
// Toast.LENGTH_LONG).show();
// // Log.d(TAG的onCreate);
//}

@覆盖
公共无效ONSTART(意向意图,诠释startId){


    用户id = intent.getExtras()的getString(USER_ID)。
    listRec =新的ArrayList<字符串>();
    要求=新SoapObject(命名空间METHOD_NAME);
    p_userId =新的PropertyInfo();
    信封=新SoapSerializationEnvelope(SoapEnvelope.VER11);
    httpTransport =新HttpTransportSE(URL);

    p_userId.setName(用户id); //定义了网络变量名
    p_userId.setValue(用户id); //定义值FNAME变量
    p_userId.setType(为String.class); //定义变量的类型
    request.addProperty(p_userId); //通行证属性到可变

    envelope.setOutputSoapObject(要求);


    尝试 {

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

        的String []行= response.toString()分裂(`)。

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

            的String []纪录=行[I] .split(〜);
            // totalDifference = 0;
            日历C = Calendar.getInstance();
            SimpleDateFormat的DF =新的SimpleDateFormat(YYYY-MM-DD);

            串CURDATE = df.format(c.getTime())的toString()。
            字符串visitDate =记录[1];

            java.util.Date CD = df.parse(CURDATE);
            java.util.Date VD = df.parse(visitDate);

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

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

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

            如果(notificationStartDate.before(newCurDate)){

                而(newOriDateVisitDate.after(newCurDate)){
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR,-1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference ++;
                    S =左;
                }
                而(newOriDateVisitDate.before(newCurDate)){
                    cOrignalVisitDate.add(Calendar.DAY_OF_YEAR,+ 1);
                    newOriDateVisitDate = cOrignalVisitDate.getTime();
                    totalDifference ++;
                    S =前;
                }
                countNotification ++;
                listRec.add(记录[2] +疫苗因:+将String.valueOf(totalDifference)
                        +天+ S);

            }

        }

        对于(INT J = 0; J< countNotification; J ++){

            NotificationManager纳米=(NotificationManager)getApplicationContext()
                    .getSystemService(getApplicationContext()NOTIFICATION_SERVICE。);
            通知注=新的通知(R.drawable.nav_down,
                    接种警报!,System.currentTimeMillis的());
            意图inNotification =新的意图(这一点,GenUserFunction.class);
            inNotification.putExtra(user_ID的,用户id);
            PendingIntent I = PendingIntent.getActivity(getBaseContext(),0,inNotification,0);
            note.setLatestEventInfo(getApplicationContext(),疫苗由于,
                    listRec.get(J),I);
            nm.notify(J,注意);


        }



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

    }赶上(例外五){
        // TODO:处理异常
        的System.out.println(e.getMessage());

    }




    // Toast.makeText(这一点,我的服务启动,Toast.LENGTH_LONG).show();

    //注意:您可以开始一个新的线程,并用它进行长时间的后台
    //从这里处理。
}





@覆盖
公共无效的onDestroy(){


在这里输入code
    super.onDestroy();

    // Toast.makeText(这一点,为MyService停止,Toast.LENGTH_LONG).show();
    // Log.d(TAG的onDestroy);
}
   }
 

解决方案
  1. 无效ONSTART(意向意图,诠释startId)是德precated,你需要使用 INT onStartCommand(意向意图,诠释标志,INT startId)代替。
  2. ONSTART(...)从被称为 onStartCommand(...)向后兼容,以及在 onStartCommand(...)返回START_STICKY值的默认实现。于是,杀后,你的服务将被系统重新启动。当服务被系统重新启动时, ONSTART(...)方法可以带一个空的意图对象, intent.getExtras() .getString(USER_ID) NullPointerException异常和服务将崩溃,以及系统重新启动......

作为结论:你需要检查意图 befor使用它的对象

When i remove my app from task manager.0 process and 1 service left. App do crash again and again what should i do to resolve it? This is my service class. I want to ask one more thing the difference between OnStart() method and OnStartCommand() method?

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) is deprecated, you need to use int onStartCommand(Intent intent, int flags, int startId) instead.
  2. onStart(...) is called from the onStartCommand(...) for backwards compatibility, and default implementation of the onStartCommand(...) returns the START_STICKY value. So, after the killing, yours service will be restarted by the system. When the service is restarted by the system, onStart(...) method can be called with a null intent object, and intent.getExtras().getString("user_Id") throws the NullPointerException, and service will be crashed, and restarted by the system...

As conclusion: you need to check the intent object for null befor using it.

这篇关于Android的后台服务崩溃,它刷出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆