2012-03-13 74 views
3

我已经实现了这个广播reciever:广播接收器不工作

public class ServiceManager extends BroadcastReceiver { 
    private final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED"; 
    private final String BOOT_ACTION_FIRST_LAUNCH = "android.intent.action.PACKAGE_FIRST_LAUNCH"; 
    private final String BOOT_ACTION_RESTARTED = "android.intent.action.PACKAGE_RESTARTED"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // All registered broadcasts are received by this 
     String action = intent.getAction(); 
     if (action.equalsIgnoreCase(BOOT_ACTION) || action.equalsIgnoreCase(BOOT_ACTION_FIRST_LAUNCH) || 
       action.equalsIgnoreCase(BOOT_ACTION_RESTARTED)) { 
      // TODO: Action 
     } 
    } 

} 

AndroidManifest.xml中

<receiver android:name="package.service.ServiceManager" > 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     <action android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" /> 
     <action android:name="android.intent.action.PACKAGE_RESTARTED" /> 
    </intent-filter> 
</receiver> 

的BOOT_COMPLETED行动工作的权利,但是,在PACKAGE_FIRST_LAUNCH和PACKAGE_RESTARTED不工作。当我启动我的应用程序时,我需要启动我的广播接收器,这就是我使用这些操作的原因。但是,当我启动或重新启动应用程序时,接收器不工作。它只在我重新启动手机时有效。我的来源有错吗?

+1

一般来说:使用字符串常量是一件好事。在意图操作字符串的情况下,你不必自己做。所有这些字符串在android框架中都有自己的常量,大部分都属于Intent类。例如。请参阅['Intent.ACTION_BOOT_COMPLETED'](http://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED)。而是使用它们,避免在自己定义它们时由于偶尔的错字而造成混淆。 ;) – 2012-03-13 11:43:31

回答

3

逻辑上看起来PACKAGE_FIRST_LAUNCH将在引导/重启后第一次运行您的应用程序后进行广播。如果您的应用程序活动堆栈被删除,然后点击您的应用程序以再次启动(如重新启动),则应广播PACKAGE_RESTARTED

但是,只要您的应用程序启动(可能来自您的第一个活动),您可以简单地通过广播自定义操作字符串来实现此目的。

5

供参考:PACKAGE_FIRST_LAUNCH只有发送到安装程序包,即无论您用于安装应用程序 - 对于大多数最终用户将是Android电子市场。

编辑:
哦,对“PACKAGE_RESTARTED”,打破一出到自己<intent-filter>,并添加

<data android:scheme="package"/> 

因为一个带有一个URI和一个明确的方案。

0

清单:

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

接收机:

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

public class AutoStart extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) 
     { 
      // Your code 
     } 
    } 
} 
0

意图android.intent.action.PACKAGE_FIRST_LAUNCH在Android的API级别12介绍如果您使用的是较小的API级别将无法正常工作。所以相应地改变你的项目设置。