gpt4 book ai didi

java - 服务在模拟器上启动但在设备上不启动

转载 作者:行者123 更新时间:2023-11-30 04:14:39 25 4
gpt4 key购买 nike

我正在尝试学习如何在 Android 中创建服务,并且我已经创建了一个非常简单的服务。问题是它在 AVD 上就像一个魅力,但在物理设备上却不是。只是它没有启动...

看一下代码:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservice" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>

服务启动器:

package com.example.myservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.myservice.MyService;

public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent pushIntent = new Intent(context, MyService.class);
//pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(pushIntent);
}
}
}

并自行服务:

package com.example.myservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
private static final String TAG = "MyService";

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

@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}

@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}

我在 android 4.0.3 上运行它

最佳答案

您需要向您的应用程序添加一个 Activity ,并且用户必须先手动启动该 Activity ,然后您的应用程序才能在 Android 3.1+ 上运行。在那之前,你的 <receiver>将被忽略。 I blogged about this ~9 months ago .

关于java - 服务在模拟器上启动但在设备上不启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10229962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com