2013-04-26 95 views
0

我敢打赌,这是重复的问题,但我需要再问一遍。服务无法启动,即使我已经把下面的代码我的android服务无法启动后启动设备

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

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 

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

    <activity 
     android:name="com.im.HomeActivity" 
     android:clearTaskOnLaunch="true" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <activity 
     android:name="com.im.ListActivity" 
     android:label="@string/title_activity_list" > 
    </activity> 

    <service 
     android:name="com.im.SyncService" 
     android:process=":remote" > 
    </service> 
</application> 

public class MyBroadcastreceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent arg1) { 
     Intent intent = new Intent(context, SyncService.class); 
     context.startService(intent); 
     Log.i("Autostart", "started");   
    } 
} 

帮助我,请。

+0

*“服务无法启动”*您如何知道?任何错误消息? 'MyBroadcastreceiver#onReceive()'是否被调用? 'startService()'返回什么? – m0skit0 2013-04-26 11:21:18

回答

0

您的BraodcastReciever被调用?

如果没有那么原因可能如下:

与3.1开始时安装的应用程序,他们是在一个 “停止”状态,所以他们将无法直到用户 明确地启动它们运行。按力量停止将返回到这个 状态。

一旦用户运行首次应用程序(并不会强制停止 吧),一切都表现为前 - 重新启动将导致接收BOOT_COMPLETED 广播等。但是,如果用户安装了 应用,则除非他们手动运行该应用,否则不会收到收到的广播 。

因此,在您的情况下,您将不得不创建启动器活动,并确保您至少启动启动器活动一次,然后您将开始接收启动事件广播。

Source

0

在Android 3.1开始,用户必须启动应用程序至少一次在你的应用程序能够接收android.intent.action.BOOT_COMPLETED事件。

另外android:allowBackup="true"被设置在您的清单文件中,请确保应用程序是而不是安装在SD卡上。如果您要保存到外部存储器,则需要设置android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE

在某些手机(如HTC)上有一个快速启动选项,如果它被激活,BOOT_COMPLETE将不会被调用。

另一种方法是使用Intent.ACTION_SCREEN_ON并检查服务是否正在运行,如果服务不在,则启动服务。更多信息here