为什么在 android 启动时我无法启动我的服务? (附代码)

why i can't start my service when the android startup ? ( code attached )

我正在尝试编写简单的基本应用程序,它将在 phone 启动时启动我的服务。

我添加了我需要的所有权限。

我在 android ( android 6.01) 上安装了应用程序。 当我重新启动我的 phone - 我看不到服务已启动或没有执行任何操作。

  1. 为什么这不起作用?
  2. 如何在 android 上调试服务?

代码:

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.NoActionBar">

    <service android:name=".MyService" android:enabled="true" android:exported="true"/>

    <receiver android:name=".MainBroadcastReceiver" android:enabled="true" android:exported="true" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
</application>



public class MainBroadcastReceiver extends BroadcastReceiver {
    public MainBroadcastReceiver(){

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, MyService.class));
    }
}




public class MyService extends Service {

private File _file;
private Timer _timer;
private FileOutputStream _fileOutputStream;

public MyService() throws IOException {

    _file = new File("/sdcard/" + "myServiceText.txt");
    _file.createNewFile();

    _fileOutputStream = openFileOutput(_file.getName(), Context.MODE_APPEND);
    _fileOutputStream.write("Ctor called".getBytes());
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}


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

    _timer = new Timer("timer");
    _timer.schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            try {
                _fileOutputStream.write("onCreate Called".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }, 0, 5000);

}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    try {
        _fileOutputStream.write("onStartCommand".getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return START_STICKY;
}

您的代码没问题,您的服务未 运行 的原因是您的应用处于 停止状态

1. Stopped state is a security procedure that allows your app to "wake itself up" only after user first manually launches it from the home screen.()
这样做 android 可以防止在您不知情的情况下在您的 phone 后台安装和 运行 恶意应用程序。

2. 如何调试后台进程?
使用后台进程时,您需要两个很棒的工具 -
首先是 adb broadcast 命令 -
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

第二个是 attach remote debugger(Android 工作室):
运行 |将调试器附加到 android 进程 (菜单中的最后一个选项)|选择您的应用进程。