在android.permission.RECEIVE_BOOT_COMPLETED中实现服务

时间:2013-02-15 12:31:18

标签: android android-service

我在网络搜索中采用以下示例。我通过一些修改实现了示例,但重启手机后显示错误。我也粘贴了我在样本中使用的源代码,请帮我解决问题

提前致谢

xml文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newtest"
android:versionCode="1"
android:versionName="1.0">

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>  
<application>  
    <receiver android:name=".BootCompletedIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>  
    <service android:name=".BackgroundService"/>  
</application>
</manifest>

广播接收器类

package com.example.newtets;

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

public class BootCompletedIntentReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {  
           Intent pushIntent = new Intent(context, BackgroundService.class);
           context.startService(pushIntent);  
    }
}
}

服务类

package com.example.newtets;

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

public class BackgroundService extends Service {

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

@Override
public void onCreate() {
    Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
    super.onCreate();
}

}

1 个答案:

答案 0 :(得分:0)

我认为你不需要比较意图..

if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {  
 .....
}

as,在xml文件中捕获应该为BOOT_COMPLETED intent执行BootCompletedIntentReceiver。