我一直在阅读其他关于在Android应用程序中获得SIGSEGV的原因的帖子。我计划在我的应用程序中寻找可能与画布使用相关的空指针,但我的SIGSEGV每次都会抛出不同的内存地址。加上code=1和code=2。如果内存地址是0x00000000,我有一个线索,它是一个空指针。

我得到的最后一个是代码=2:

A/libc(4969): Fatal signal 11 (SIGSEGV) at 0x42a637d9 (code=2)

有什么建议吗?

I have a suspect, but I'm not keen on experimenting with it yet. My app uses the OSMDroid API for offline mapping. The OverlayItem class represents markers/nodes on the map. I have a Service that collects data via the network to populate the OverlayItem which are then displayed on the map. In an effort to simplify my design, I extended OverlayItem into my own NodeOverlayItem class, which includes some addition attributes I use in the UI Activity and in the Service. This gave me a single point of Item information for the UI and Service. I used Intents to broadcast to the Activity to refresh the UI map when something changed. The Activity binds to the Service and there's a Service method to get the list of NodeOverlayItem's. I think it might be the OSMDroid API's use of OverlayItem, and my Service updating node information at the same time. (a concurrency issue)

As I write this I think that's really the problem. The headache isn't splitting out the Node and OverlayItem from NodeOverlayItem, it's that the Activity will need some data from the Node, that the Service holds. Plus when the Activity is created (onResume, etc...) the OverlayItem objects will need to be re-created from the Node data that the Service has been maintaining while the Activity was away. e.g. You start the app, the Service collects data, the UI displays it, you go to Home, then back to the app, the Activity will need to pull and re-create the OverlayItem's from the latest Service node data.

我知道这不是一个很好的问题。就好像我所有的SO问题都是小众或模糊的。如果有人对如何解释这些SIGSEGV错误有建议,将不胜感激!

更新 下面是在调试会话期间捕获的最新崩溃。我有3个这样的设备用于测试,当我在开发和测试时,它们都不会可靠地崩溃。我额外添加了一些内容,以便能够注意到GC日志记录。您可以看到,这个问题可能与内存耗尽无关。

03-03 02:02:38.328: I/CommService(7477): Received packet from: 192.168.1.102
03-03 02:02:38.328: I/CommService(7477): Already processed this packet. It's a re-broadcast from another node, or from myself. It's not a repeat broadcast though.
03-03 02:02:38.406: D/CommService(7477): Checking OLSRd info...
03-03 02:02:38.460: D/CommService(7477): Monitoring nodes...
03-03 02:02:38.515: D/dalvikvm(7477): GC_CONCURRENT freed 2050K, 16% free 17151K/20359K, paused 3ms+6ms
03-03 02:02:38.515: I/CommService(7477): Received packet from: 192.168.1.102
03-03 02:02:38.515: D/CommService(7477): Forwarding packet (4f68802cf10684a83ac4936ebb3c934d) along to other nodes.
03-03 02:02:38.609: I/CommService(7477): Received packet from: 192.168.1.100
03-03 02:02:38.609: D/CommService(7477): Forwarding packet (e4bc81e91ec92d06f83e03068f52ab4) along to other nodes.
03-03 02:02:38.609: D/CommService(7477): Already processed this packet: 4204a5b27745ffe5e4f8458e227044bf
03-03 02:02:38.609: A/libc(7477): Fatal signal 11 (SIGSEGV) at 0x68f52abc (code=1)
03-03 02:02:38.914: I/DEBUG(4008): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
03-03 02:02:38.914: I/DEBUG(4008): Build fingerprint: 'Lenovo/IdeaTab_A1107/A1107:4.0.4/MR1/eng.user.20120719.150703:user/release-keys'
03-03 02:02:38.914: I/DEBUG(4008): pid: 7477, tid: 7712  >>> com.test.testm <<<
03-03 02:02:38.914: I/DEBUG(4008): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 68f52abc
03-03 02:02:38.914: I/DEBUG(4008):  r0 68f52ab4  r1 412ef268  r2 4d9c3bf4  r3 412ef268
03-03 02:02:38.914: I/DEBUG(4008):  r4 001ad8f8  r5 4d9c3bf4  r6 412ef268  r7 4c479df8
03-03 02:02:38.914: I/DEBUG(4008):  r8 4d9c3c0c  r9 4c479dec  10 46cf260a  fp 4d9c3c24
03-03 02:02:38.914: I/DEBUG(4008):  ip 40262a04  sp 4d9c3bc8  lr 402d01dd  pc 402d0182  cpsr 00000030
03-03 02:02:38.914: I/DEBUG(4008):  d0  00000001000c0102  d1  3a22364574614c7d
03-03 02:02:38.914: I/DEBUG(4008):  d2  403fc0000000007d  d3  363737343433350a
03-03 02:02:38.914: I/DEBUG(4008):  d4  49544341223a2273  d5  6f6567222c224556
03-03 02:02:38.914: I/DEBUG(4008):  d6  3a223645676e6f4c  d7  000000013835372d
03-03 02:02:38.914: I/DEBUG(4008):  d8  0000000000000000  d9  4040000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d10 0000000000000000  d11 4040000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d12 4040000000000000  d13 0000000000000021
03-03 02:02:38.914: I/DEBUG(4008):  d14 0000000000000000  d15 0000000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d16 3fe62e42fefa39ef  d17 3ff0000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d18 3fe62e42fee00000  d19 0000000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d20 0000000000000000  d21 3ff0000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d22 4028000000000000  d23 3ff0000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d24 0000000000000000  d25 3ff0000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d26 0000000000000000  d27 c028000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d28 0000000000000000  d29 3ff0000000000000
03-03 02:02:38.914: I/DEBUG(4008):  d30 3ff0000000000000  d31 3fecccccb5c28f6e
03-03 02:02:38.914: I/DEBUG(4008):  scr 60000013
03-03 02:02:39.046: I/DEBUG(4008):          #00  pc 0006b182  /system/lib/libcrypto.so (EVP_DigestFinal_ex)
03-03 02:02:39.046: I/DEBUG(4008):          #01  pc 0006b1d8  /system/lib/libcrypto.so (EVP_DigestFinal)
03-03 02:02:39.054: I/DEBUG(4008):          #02  pc 0001f814  /system/lib/libnativehelper.so
03-03 02:02:39.054: I/DEBUG(4008):          #03  pc 0001ec30  /system/lib/libdvm.so (dvmPlatformInvoke)
03-03 02:02:39.054: I/DEBUG(4008):          #04  pc 00058c70  /system/lib/libdvm.so (_Z16dvmCallJNIMethodPKjP6JValuePK6MethodP6Thread)
03-03 02:02:39.054: I/DEBUG(4008): code around pc:
03-03 02:02:39.054: I/DEBUG(4008): 402d0160 0003151e 4604b570 f7ff460d 4620ff81  ....p..F.F.... F
03-03 02:02:39.054: I/DEBUG(4008): 402d0170 f7ff4629 bd70ff93 4604b570 460e6800  )F....p.p..F.h.F
03-03 02:02:39.054: I/DEBUG(4008): 402d0180 68834615 dd062b40 21fa4810 44784a10  .F.h@+...H.!.JxD
03-03 02:02:39.054: I/DEBUG(4008): 402d0190 f7c8447a 6821f80f 698a4620 47904631  zD....!h F.i1F.G
03-03 02:02:39.054: I/DEBUG(4008): 402d01a0 b1154606 68836820 6822602b b12b6a13  .F.. h.h+`"h.j+.
03-03 02:02:39.054: I/DEBUG(4008): code around lr:
03-03 02:02:39.054: I/DEBUG(4008): 402d01bc 68e06821 21006c4a ea0af7c4 bd704630  !h.hJl.!....0Fp.
03-03 02:02:39.054: I/DEBUG(4008): 402d01cc 00031492 000314b5 4604b570 ffcef7ff  ........p..F....
03-03 02:02:39.054: I/DEBUG(4008): 402d01dc 46204605 ff12f7ff bd704628 4604b573  .F F....(Fp.s..F
03-03 02:02:39.054: I/DEBUG(4008): 402d01ec 2102460d fb36f002 42ab6823 b123d020  .F.!..6.#h.B .#.
03-03 02:02:39.054: I/DEBUG(4008): 402d01fc b1136c5b f7c868e0 68a0fccf 05c26025  [l...h.....h%`..
03-03 02:02:39.054: I/DEBUG(4008): memory map around addr 68f52abc:
03-03 02:02:39.054: I/DEBUG(4008): 4d8c5000-4d9c4000 
03-03 02:02:39.054: I/DEBUG(4008): (no map for address)
03-03 02:02:39.054: I/DEBUG(4008): b0001000-b0009000 /system/bin/linker
03-03 02:02:39.054: I/DEBUG(4008): stack:
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b88  408d1f90  /system/lib/libdvm.so
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b8c  412ef258  /dev/ashmem/dalvik-heap (deleted)
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b90  00000001  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b94  408d6c58  /system/lib/libdvm.so
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b98  408d6fa8  /system/lib/libdvm.so
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3b9c  4c479dec  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3ba0  46cf260a  /system/framework/core.odex
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3ba4  408735e7  /system/lib/libdvm.so
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3ba8  412ef258  /dev/ashmem/dalvik-heap (deleted)
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bac  002bf070  [heap]
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bb0  412ef258  /dev/ashmem/dalvik-heap (deleted)
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bb4  00000000  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bb8  412ef268  /dev/ashmem/dalvik-heap (deleted)
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bbc  00000000  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bc0  df0027ad  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bc4  00000000  
03-03 02:02:39.054: I/DEBUG(4008): #00 4d9c3bc8  001ad8f8  [heap]
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bcc  002ae0b8  [heap]
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bd0  00000004  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bd4  402d01dd  /system/lib/libcrypto.so
03-03 02:02:39.054: I/DEBUG(4008): #01 4d9c3bd8  001ad8f8  [heap]
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3bdc  002ae0b8  [heap]
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3be0  00000004  
03-03 02:02:39.054: I/DEBUG(4008):     4d9c3be4  4024e817  /system/lib/libnativehelper.so
03-03 02:02:39.406: D/CommService(7477): Checking OLSRd info...
03-03 02:02:39.500: D/CommService(7477): Monitoring nodes...
03-03 02:02:39.500: D/dalvikvm(7477): GC_FOR_ALLOC freed 2073K, 16% free 17118K/20359K, paused 51ms
03-03 02:02:39.632: D/dalvikvm(7477): GC_CONCURRENT freed 1998K, 16% free 17162K/20359K, paused 2ms+4ms
03-03 02:02:40.406: D/CommService(7477): Checking OLSRd info...
03-03 02:02:40.445: D/CommService(7477): Monitoring nodes...
03-03 02:02:40.562: D/dalvikvm(7477): GC_CONCURRENT freed 2045K, 16% free 17158K/20359K, paused 3ms+4ms
03-03 02:02:41.406: D/CommService(7477): Checking OLSRd info...
03-03 02:02:41.445: D/CommService(7477): Monitoring nodes...
03-03 02:02:41.531: D/dalvikvm(7477): GC_CONCURRENT freed 2045K, 16% free 17154K/20359K, paused 3ms+12ms
03-03 02:02:42.406: D/CommService(7477): Checking OLSRd info...
03-03 02:02:42.445: D/CommService(7477): Monitoring nodes...
03-03 02:02:42.507: D/dalvikvm(7477): GC_CONCURRENT freed 2068K, 16% free 17128K/20359K, paused 3ms+4ms
03-03 02:02:42.679: D/dalvikvm(7477): GC_CONCURRENT freed 2006K, 16% free 17161K/20359K, paused 2ms+12ms
03-03 02:02:43.140: I/BootReceiver(1236): Copying /data/tombstones/tombstone_05 to DropBox (SYSTEM_TOMBSTONE)
03-03 02:02:43.210: D/dalvikvm(1236): GC_FOR_ALLOC freed 912K, 17% free 10207K/12295K, paused 62ms
03-03 02:02:43.265: D/dalvikvm(1236): GC_FOR_ALLOC freed 243K, 16% free 10374K/12295K, paused 49ms
03-03 02:02:43.265: I/dalvikvm-heap(1236): Grow heap (frag case) to 10.507MB for 196628-byte allocation

在android中实现服务时,START_STICKY和START_NOT_STICKY之间的区别是什么?谁能举出一些标准的例子??

是否有可靠的方法从服务中获取Context ?

我想为ACTION_PHONE_STATE_CHANGED注册一个广播接收器,但我不需要我的应用程序总是得到这个信息,所以我没有把它放在Manifest中。

然而,当我需要这些信息时,我不能让GC杀死广播接收器,所以我在服务中注册了广播接收器。

因此,我需要一个Context来调用registerReceiver()。 当我不再需要ACTION_PHONE_STATE_CHANGED时,我注销了它。

任何建议吗?

我一直试图在设备在android上启动时启动一项服务,但我无法让它工作。我在网上看了一些链接,但没有一个代码工作。我是不是忘了什么?

AndroidManifest.xml

<receiver
    android:name=".StartServiceAtBootReceiver"
    android:enabled="true"
    android:exported="false"
    android:label="StartServiceAtBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action._BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name="com.test.RunService"
    android:enabled="true" />

BroadcastReceiver

public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent serviceLauncher = new Intent(context, RunService.class);
        context.startService(serviceLauncher);
        Log.v("TEST", "Service loaded at start");
    }
}

我找不到一个令人满意的答案,所以我们来看看:Activity/Service.getApplication()和Context.getApplicationContext()是怎么回事?

在我们的应用程序中,两者返回相同的对象。然而,在ActivityTestCase中,模拟应用程序将使getApplication()返回模拟,但getApplicationContext仍将返回一个不同的上下文实例(由Android注入)。那是虫子吗?是故意的吗?

我一开始都不明白有什么区别。在测试套件之外是否存在两个调用可能返回不同对象的情况?什么时候,为什么?此外,为什么getApplication定义在活动和服务上,而不是在上下文上?不应该总是有一个有效的应用程序实例从任何地方可用吗?

在应用程序启动时,应用程序启动应该执行一些网络任务的服务。 在目标API级别26后,我的应用程序无法在Android 8.0后台启动服务。

导致原因:java.lang.IllegalStateException:不允许启动 服务意图{ cmp = my.app.tt / com.my.service }: app是在后台uid UidRecord{90372b1 u0a136 CEM空闲procs:1 seq (0, 0, 0)}

我的理解是: 后台执行限制

startService()方法现在抛出一个IllegalStateException 针对Android 8.0的应用程序尝试使用这种方法 不允许创建后台服务。

“在不被允许的情况下”——这实际上是什么意思?以及如何修复它。我不想把我的服务设置为前台

我找不到任何关于如何在活动和服务之间发送消息的示例,而且我已经花了太多时间来解决这个问题。这里有一个示例项目供其他人参考。

此示例允许您直接启动或停止服务,并分别与服务绑定/解除绑定。业务运行时,以10hz的频率递增一个数字。如果活动绑定到服务,它将显示当前值。数据传输作为一个整数和字符串,所以你可以看到如何做到这两种不同的方式。活动中还有一些按钮用于向服务发送消息(更改增量值)。

截图:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleservice"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name=".MyService"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

res价值观喝strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExampleService</string>
    <string name="service_started">Example Service started</string>
    <string name="service_label">Example Service Label</string>
</resources>

res\layout\main.xml:

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service" >
    </Button>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Stop Service" >
    </Button>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/RelativeLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnBind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind to Service" >
    </Button>

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Unbind from Service" >
    </Button>
</RelativeLayout>

<TextView
    android:id="@+id/textStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Status Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textIntValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Integer Value Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textStrValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="String Value Goes Here"
    android:textSize="24sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnUpby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Increment by 1" >
    </Button>

    <Button
        android:id="@+id/btnUpby10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Increment by 10" >
    </Button>
</RelativeLayout>

src \ com.exampleservice \ MainActivity.java:

package com.exampleservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    TextView textStatus, textIntValue, textStrValue;
    Messenger mService = null;
    boolean mIsBound;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyService.MSG_SET_INT_VALUE:
                textIntValue.setText("Int Message: " + msg.arg1);
                break;
            case MyService.MSG_SET_STRING_VALUE:
                String str1 = msg.getData().getString("str1");
                textStrValue.setText("Str Message: " + str1);
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            textStatus.setText("Attached.");
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            textStatus.setText("Disconnected.");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);
        textStatus = (TextView)findViewById(R.id.textStatus);
        textIntValue = (TextView)findViewById(R.id.textIntValue);
        textStrValue = (TextView)findViewById(R.id.textStrValue);
        btnUpby1 = (Button)findViewById(R.id.btnUpby1);
        btnUpby10 = (Button)findViewById(R.id.btnUpby10);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        btnUnbind.setOnClickListener(btnUnbindListener);
        btnUpby1.setOnClickListener(btnUpby1Listener);
        btnUpby10.setOnClickListener(btnUpby10Listener);

        restoreMe(savedInstanceState);

        CheckIfServiceIsRunning();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("textStatus", textStatus.getText().toString());
        outState.putString("textIntValue", textIntValue.getText().toString());
        outState.putString("textStrValue", textStrValue.getText().toString());
    }
    private void restoreMe(Bundle state) {
        if (state!=null) {
            textStatus.setText(state.getString("textStatus"));
            textIntValue.setText(state.getString("textIntValue"));
            textStrValue.setText(state.getString("textStrValue"));
        }
    }
    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
        }
    };
    private OnClickListener btnUpby1Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(1);
        }
    };
    private OnClickListener btnUpby10Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(10);
        }
    };
    private void sendMessageToService(int intvaluetosend) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                }
            }
        }
    }


    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
            textStatus.setText("Unbinding.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        }
        catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }
}

src \ com.exampleservice \ MyService.java:

package com.exampleservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private NotificationManager nm;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.


    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private void sendMessageToUI(int intvaluetosend) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
                b.putString("str1", "ab" + intvaluetosend + "cd");
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                mClients.get(i).send(msg);

            }
            catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
        isRunning = true;
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }


    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
            sendMessageToUI(counter);

        }
        catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {timer.cancel();}
        counter=0;
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}

我正在寻找一个可以用IntentService完成但不能用Service完成的示例(反之亦然)?

我还认为IntentService在不同的线程中运行,而Service则不运行。因此,就我所见,在自己的线程中启动服务就像启动IntentService一样。这是正确的吗?

如何查看后台服务是否正在运行?

我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。