2017-06-30 419 views
1

我遇到了一個奇怪的問題,我無法理解,因爲該應用沒有給出任何碰撞日誌或任何其他消息,我可以按照它來搜索問題。Android:getSystemService(Context.ACTIVITY_SERVICE)在服務中不起作用

我發動從我的活動,在這個服務我試圖找出哪些是處於錯誤狀態,但是當我的代碼達到行

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

然後應用程序停止工作進程的數目服務。當我調試我的應用程序時,我發現在點擊上面的行後,調試器導航到cleanUpPendingRemoveWindows()中的文件ActivityThread.java,並顯示消息「源代碼與字節碼不匹配」。我無法理解爲什麼會發生這種情況?

我的代碼是:

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; 
} 
} 
+0

你在哪裏打這個服務?有沒有辦法android getSystemService不工作,也許你需要添加權限或只是忘記調用方法 –

+0

我從另一個活動調用此服務名爲Senddata_1。 – Pagar

+0

你應該在onStartCommand中使用這個方法而不是構造函數。您不能通過創建新對象直接調用服務。在這種情況下,上下文將爲空。在這樣的活動中調用你的服務:startService(new Intent(this,Senddata_1 .class)); –

回答

1

應用程序不提供任何崩潰日誌或者我可以按照搜索的問題,任何其他消息。

哦,我強烈懷疑它的確如此。

當我的代碼到達行......那麼應用程序停止工作。

那是因爲你想在你onCreate()方法調用super.onCreate()之前調用從Service繼承的方法。最典型的例外將是NullPointerException

替換爲你的構造:

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

然後,當您啓動該服務,您的find_out_process_in_error_state()方法將被調用,當它應該是安全的它打電話getSystemService()

+0

感謝您的建議。它的確按照你的建議替換了構造函數。 – Pagar