android 服务在启动时启动并强制停止

发布于 2024-12-17 18:40:07 字数 8576 浏览 1 评论 0原文

我是 Android 新手..我试图编写 Android 服务,该服务将在设备启动时启动。当我使用模拟器运行应用程序时,我可以在“adb logcat”中看到我的调试语句(system.outs);这意味着启动完成后将调用我的服务。但根据日志,“onStart”服务方法中的整个代码没有被执行。日志未显示所有预期的 system.outs。

下面是显示“强制停止服务”语句的日志(以粗体标记):-

**D/Exchange(  222): BootReceiver onReceive
D/EAS SyncManager(  222): !!! EAS SyncManager, onCreate
I/ActivityManager(   58): Start proc com.webapps.service for broadcast com.webap
ps.service/.MyStartupIntentReceiver: pid=232 uid=10038 gids={1015}
D/EAS SyncManager(  222): !!! EAS SyncManager, onStartCommand
D/EAS SyncManager(  222): !!! EAS SyncManager, stopping self
D/Eas Debug(  222): Logging:
D/EAS SyncManager(  222): !!! EAS SyncManager, onDestroy
**I/System.out(  232): **************MyStartupIntentReceiver******************
I/System.out(  232): **************Service created******************
I/ActivityManager(   58): Start proc com.android.music for broadcast com.android
.music/.MediaAppWidgetProvider: pid=241 uid=10022 gids={3003, 1015}
**I/System.out(  232): **************Service started****************
I/System.out(  232): *********Current date is :=>  2011/Nov/24 11:02:34**
I/ActivityManager(   58): Start proc com.android.quicksearchbox for broadcast co
m.android.quicksearchbox/.SearchWidgetProvider: pid=247 uid=10012 gids={3003}
I/ActivityThread(  247): Publishing provider com.android.quicksearchbox.google:
com.android.quicksearchbox.google.GoogleSuggestionProvider
I/ActivityManager(   58): Start proc com.android.protips for broadcast com.andro
id.protips/.ProtipWidget: pid=255 uid=10007 gids={}
D/PackageParser(   58): Scanning package: /data/app/vmdl34597.tmp
W/PackageParser(   58): Unknown element under <application>: uses-permission at
/data/app/vmdl34597.tmp Binary XML file line #18
I/PackageParser(   58): com.webapps.service: compat added android.permission.WRI
TE_EXTERNAL_STORAGE android.permission.READ_PHONE_STATE
D/MediaScanner(  195):  prescan time: 2646ms
D/MediaScanner(  195):     scan time: 91ms
D/MediaScanner(  195): postscan time: 1ms
D/MediaScanner(  195):    total time: 2738ms
I/PackageManager(   58): Removing non-system package:com.webapps.service
D/dalvikvm(  128): GC_EXTERNAL_ALLOC freed 4610 objects / 268504 bytes in 125ms
D/PackageManager(   58): Scanning package com.webapps.service
I/PackageManager(   58): Package com.webapps.service codePath changed from /data
/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk; Retaining
 data and using new
I/PackageManager(   58): /data/app/com.webapps.service-1.apk changed; unpacking
D/installd(   34): DexInv: --- BEGIN '/data/app/com.webapps.service-1.apk' ---
I/Launcher.Model(  128): not binding apps: no Launcher activity
D/dalvikvm(  128): GC_EXPLICIT freed 1595 objects / 79016 bytes in 251ms
D/dalvikvm(  261): DexOpt: load 200ms, verify 217ms, opt 2ms
D/installd(   34): DexInv: --- END '/data/app/com.webapps.service-1.apk' (succes
s) ---
W/PackageManager(   58): Code path for pkg : com.webapps.service changing from /
data/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk
W/PackageManager(   58): Resource path for pkg : com.webapps.service changing fr
om /data/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk
D/PackageManager(   58):   Services: com.webapps.service.SimpleService
D/PackageManager(   58):   Receivers: com.webapps.service.MyStartupIntentReceive
r
I/installd(   34): move /data/dalvik-cache/data@[email protected]@cl
asses.dex -> /data/dalvik-cache/data@[email protected]@classes.dex
D/PackageManager(   58): New package installed in /data/app/com.webapps.service-
1.apk
D/MediaScannerService(  195): done scanning volume internal
I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038
W/ActivityManager(   58): Scheduling restart of crashed service com.webapps.serv
ice/.SimpleService in 13004ms
I/Process (   58): Sending signal. PID: 232 SIG: 9
**I/ActivityManager(   58):   Force stopping service ServiceRecord{4502c7e0 com.we
bapps.service/.SimpleService}**
W/ActivityManager(   58): setProcessForeground called on unknown pid: 232
E/JavaBinder(   58): !!! FAILED BINDER TRANSACTION !!!
I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038
**I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038**
D/dalvikvm(  128): GC_EXPLICIT freed 6910 objects / 354424 bytes in 210ms 

下面是我的代码

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.webapps.service"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <!--<activity android:name=".ServiceController"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity> -->

        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

        <receiver android:name=".MyStartupIntentReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

       <service android:name=".SimpleService">
            <intent-filter>
                <action android:name="com.wissen.startatboot.SimpleService" />
            </intent-filter>
        </service>

    </application>
</manifest>

package com.webapps.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

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

public class SimpleService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
          return null;
    }
    @Override
    public void onCreate() {
          super.onCreate();
          System.out.println("**************Service created****************");
          Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
          super.onDestroy();
          System.out.println("**************Service destroyed****************");
          Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
    }

    public void onStart(Intent intent, int startId) {

        super.onStart(intent, startId);
        System.out.println("**************Service started****************");
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        int cnt=0;
        while (true)
        {
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
        String dateNow = formatter.format(currentDate.getTime());
        System.out.println("*********Current date is :=>  " + dateNow);
        cnt++;
        try{
        Thread.sleep (20000);
        }catch (Exception e){System.out.println(e);}
        if (cnt == 4)
            break;
        }
        System.out.println("********CNT*************  " + cnt);
    }
}

package com.webapps.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyStartupIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.wissen.startatboot.SimpleService");
    System.out.println("**************MyStartupIntentReceiver****************");    
    context.startService(serviceIntent);
}
}

SimpleService.java 是在包 com.webapps.service 下定义的>;而MyStartupIntentReceiverintentAction设置为com.wissen.startatboot.SimpleService

这是否会导致我的服务强制停止?

I am new to Android.. I was trying to write android service which will be started when device starts. When I run the application with simulator, I am able to see the my debug statements (system.outs) in "adb logcat"; which means my service is getting invoked when bootup is completed. But as per log, entire code in 'onStart' service method is not getting executed. Log is not showing all expected system.outs.

Below is the log showing 'force stopping service' statements (marked in BOLD):-

**D/Exchange(  222): BootReceiver onReceive
D/EAS SyncManager(  222): !!! EAS SyncManager, onCreate
I/ActivityManager(   58): Start proc com.webapps.service for broadcast com.webap
ps.service/.MyStartupIntentReceiver: pid=232 uid=10038 gids={1015}
D/EAS SyncManager(  222): !!! EAS SyncManager, onStartCommand
D/EAS SyncManager(  222): !!! EAS SyncManager, stopping self
D/Eas Debug(  222): Logging:
D/EAS SyncManager(  222): !!! EAS SyncManager, onDestroy
**I/System.out(  232): **************MyStartupIntentReceiver******************
I/System.out(  232): **************Service created******************
I/ActivityManager(   58): Start proc com.android.music for broadcast com.android
.music/.MediaAppWidgetProvider: pid=241 uid=10022 gids={3003, 1015}
**I/System.out(  232): **************Service started****************
I/System.out(  232): *********Current date is :=>  2011/Nov/24 11:02:34**
I/ActivityManager(   58): Start proc com.android.quicksearchbox for broadcast co
m.android.quicksearchbox/.SearchWidgetProvider: pid=247 uid=10012 gids={3003}
I/ActivityThread(  247): Publishing provider com.android.quicksearchbox.google:
com.android.quicksearchbox.google.GoogleSuggestionProvider
I/ActivityManager(   58): Start proc com.android.protips for broadcast com.andro
id.protips/.ProtipWidget: pid=255 uid=10007 gids={}
D/PackageParser(   58): Scanning package: /data/app/vmdl34597.tmp
W/PackageParser(   58): Unknown element under <application>: uses-permission at
/data/app/vmdl34597.tmp Binary XML file line #18
I/PackageParser(   58): com.webapps.service: compat added android.permission.WRI
TE_EXTERNAL_STORAGE android.permission.READ_PHONE_STATE
D/MediaScanner(  195):  prescan time: 2646ms
D/MediaScanner(  195):     scan time: 91ms
D/MediaScanner(  195): postscan time: 1ms
D/MediaScanner(  195):    total time: 2738ms
I/PackageManager(   58): Removing non-system package:com.webapps.service
D/dalvikvm(  128): GC_EXTERNAL_ALLOC freed 4610 objects / 268504 bytes in 125ms
D/PackageManager(   58): Scanning package com.webapps.service
I/PackageManager(   58): Package com.webapps.service codePath changed from /data
/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk; Retaining
 data and using new
I/PackageManager(   58): /data/app/com.webapps.service-1.apk changed; unpacking
D/installd(   34): DexInv: --- BEGIN '/data/app/com.webapps.service-1.apk' ---
I/Launcher.Model(  128): not binding apps: no Launcher activity
D/dalvikvm(  128): GC_EXPLICIT freed 1595 objects / 79016 bytes in 251ms
D/dalvikvm(  261): DexOpt: load 200ms, verify 217ms, opt 2ms
D/installd(   34): DexInv: --- END '/data/app/com.webapps.service-1.apk' (succes
s) ---
W/PackageManager(   58): Code path for pkg : com.webapps.service changing from /
data/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk
W/PackageManager(   58): Resource path for pkg : com.webapps.service changing fr
om /data/app/com.webapps.service-2.apk to /data/app/com.webapps.service-1.apk
D/PackageManager(   58):   Services: com.webapps.service.SimpleService
D/PackageManager(   58):   Receivers: com.webapps.service.MyStartupIntentReceive
r
I/installd(   34): move /data/dalvik-cache/data@[email protected]@cl
asses.dex -> /data/dalvik-cache/data@[email protected]@classes.dex
D/PackageManager(   58): New package installed in /data/app/com.webapps.service-
1.apk
D/MediaScannerService(  195): done scanning volume internal
I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038
W/ActivityManager(   58): Scheduling restart of crashed service com.webapps.serv
ice/.SimpleService in 13004ms
I/Process (   58): Sending signal. PID: 232 SIG: 9
**I/ActivityManager(   58):   Force stopping service ServiceRecord{4502c7e0 com.we
bapps.service/.SimpleService}**
W/ActivityManager(   58): setProcessForeground called on unknown pid: 232
E/JavaBinder(   58): !!! FAILED BINDER TRANSACTION !!!
I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038
**I/ActivityManager(   58): Force stopping package com.webapps.service uid=10038**
D/dalvikvm(  128): GC_EXPLICIT freed 6910 objects / 354424 bytes in 210ms 

Below is my code

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.webapps.service"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <!--<activity android:name=".ServiceController"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity> -->

        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

        <receiver android:name=".MyStartupIntentReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

       <service android:name=".SimpleService">
            <intent-filter>
                <action android:name="com.wissen.startatboot.SimpleService" />
            </intent-filter>
        </service>

    </application>
</manifest>

package com.webapps.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

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

public class SimpleService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
          return null;
    }
    @Override
    public void onCreate() {
          super.onCreate();
          System.out.println("**************Service created****************");
          Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
          super.onDestroy();
          System.out.println("**************Service destroyed****************");
          Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
    }

    public void onStart(Intent intent, int startId) {

        super.onStart(intent, startId);
        System.out.println("**************Service started****************");
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        int cnt=0;
        while (true)
        {
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
        String dateNow = formatter.format(currentDate.getTime());
        System.out.println("*********Current date is :=>  " + dateNow);
        cnt++;
        try{
        Thread.sleep (20000);
        }catch (Exception e){System.out.println(e);}
        if (cnt == 4)
            break;
        }
        System.out.println("********CNT*************  " + cnt);
    }
}

package com.webapps.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyStartupIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.wissen.startatboot.SimpleService");
    System.out.println("**************MyStartupIntentReceiver****************");    
    context.startService(serviceIntent);
}
}

SimpleService.java is defined under package com.webapps.service; whereas MyStartupIntentReceiver sets intentAction as com.wissen.startatboot.SimpleService.

Is this causing my service to force stop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヤ经典坏疍 2024-12-24 18:40:08

不要在 onStart 中工作!。 Android 将等待它返回,但由于时间原因它永远不会返回。超时将会触发,Android 将终止您的服务!

你在其他线程中做事,例如 AsyncTask

Don't do you work in onStart!. Android will wait till it returns, which it never does due the while. A timeout will fire and Android will kill your service!

Do you things in an other thread, e.g. AsyncTask

标点 2024-12-24 18:40:08

如果删除 while(true) 循环,您的服务会崩溃吗?我猜想 onStart 预计不会执行太长时间。
此外,Service 不是在单独的线程中执行的。

Does your service crash if you remove the while(true) loop? I would guess onStart is not expected to execute for too long.
Also, Service is not executed in a separate thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文