Android: getSystemService(Context.ACTIVITY_SERVICE) 在服务中不工作

Android: getSystemService(Context.ACTIVITY_SERVICE) is not working in Service

我遇到了一个我无法理解的奇怪问题,因为应用程序没有提供任何崩溃日志或任何其他消息,我可以按照这些消息来搜索问题。

我从我的 activity 启动了一个服务,在这个服务中,我试图找出处于错误状态的进程的数量,但是当我的代码到达行

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

然后应用停止工作。当我调试我的应用程序时,我发现在点击上面的行后,调试器导航到 cleanUpPendingRemoveWindows() 中的文件 ActivityThread.java,并显示一条消息 "Source code does not match the byte code"。我无法理解为什么会这样?

我的代码是:

import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

public class Senddata_1 extends Service {

String TAG = "uEarn:Senddata_1";

public void find_out_process_in_error_state(){

    List<ActivityManager.ProcessErrorStateInfo> processErrorStateInfos;

    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

    processErrorStateInfos = am.getProcessesInErrorState();

    if(processErrorStateInfos != null) {
        for (ActivityManager.ProcessErrorStateInfo pes : processErrorStateInfos) {
            Log.e(TAG, "Process in Error state" + pes.processName);
            Log.e(TAG, "Process error messga" + pes.shortMsg);

            message = message + "<p>Process in Error state:" + pes.processName + ", error message:" + pes.shortMsg + "</p>\n";
        }
    }
    return;
}

 public Senddata_1() {

    // TODO: Get the Filename through the intent

    Log.e(TAG, "Inside service Senddata_1");

    find_out_process_in_error_state();

}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
   //        return;
}
}

the app does not give any crash log or any other message which I can follow to search the problem.

哦,我强烈怀疑是的。

when my code reaches to the line... then the app stops working.

那是因为您试图在 onCreate() 方法中调用 super.onCreate() 之前调用从 Service 继承的方法。最典型的异常是 NullPointerException.

将您的构造函数替换为:

@Override
public void onCreate() {
  super.onCreate();
  find_out_process_in_error_state();
}

然后,当您启动该服务时,您的 find_out_process_in_error_state() 方法将被调用,此时调用 getSystemService().

应该是安全的