无法使用广播接收器启动服务

0 android android-intent

我想使用此代码使用BroadcastReceiver启动服务

public void onReceive(Context context, Intent intent) {

    Intent myIntent = new Intent(context,BlueToothService.class);   

    context.startService(myIntent);

}
Run Code Online (Sandbox Code Playgroud)

但无法启动该服务.我还在清单中注册了服务和接收者.

我也有一个疑问,我们可以在没有活动的情况下使用广播接收器吗?

这是我的服务类

public class BlueToothService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onStartCommand(Intent intent, int startId) {

    super.onStart(intent, startId);
    Toast.makeText(this, "service Started", Toast.LENGTH_LONG);
    doBluetoothJob();

}
Run Code Online (Sandbox Code Playgroud)

我的清单文件看起来像这样.

<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BROADCAST_SMS" />

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

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

    <receiver android:name="com.simsys.bt.DemoBT" >
    </receiver>

    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
Run Code Online (Sandbox Code Playgroud)

swi*_*Boy 6

这与我合作我创建了一个接收器.

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, "MyReceiver Started", Toast.LENGTH_SHORT).show();
        Intent myIntent=new Intent(context,MyService.class);        
        context.startService(myIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个简单的服务

public class MyService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在清单文件中输入广播接收器和服务

<application android:icon="@drawable/icon" android:label="@string/app_name">        
<service
    android:enabled="true"
    android:name=".MyService">
    <intent-filter>
        <action
            android:name = "com.rdc.MyService">
        </action>
    </intent-filter>
  </service>
  <receiver
    android:enabled="true"
    android:name=".MyReceiver">
    <intent-filter>
        <action android:name = "android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
  </receiver>
</application>
Run Code Online (Sandbox Code Playgroud)

现在重启后,模拟器Toast将出现.