为什么启动设备android后服务不会自动启动

时间:2012-09-07 11:16:57

标签: android android-service android-alarms

我将自动启动编码为:

public class AutoStart extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            SetAlarm(context);
        }       

    }

    public void SetAlarm(Context context) {
        AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, ServiceUpdateData.class);
        // PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        PendingIntent pi = PendingIntent.getService(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 30);// 
        int dbtime = 10;

        int time = 1000 * 60 * dbtime;
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                time, pi); // Millisec * Second * Minute
        Toast.makeText(context, "Service Started Again", Toast.LENGTH_LONG)
                .show();
    }
}

我在androidmanifest.xml中添加了

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

为什么启动设备android后我的服务不会自动启动。 你能救我吗?

2 个答案:

答案 0 :(得分:1)

不要忘记将Intent-Filter设置为BOOT_COMPLETED

像:

<receiver android:name=".AutoStart">
    <intent-filter>
        <action
            android:name ="android.intent.action.BOOT_COMPLETED">
        </action>
    </intent-filter>
</receiver>

答案 1 :(得分:1)

   <receiver android:name="yourpackageName.classname"

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