服务是否可以接收package.Added意图

时间:2012-07-15 05:01:56

标签: android android-intent android-service

我想在添加新包时显示通知。我找到了清单文件所需的代码!我无法弄清楚的是如何在我的服务中捕获广播。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

您可以注册PACKAGE_INSTALLPACKAGE_ADDED Receiver for Receiving程序包安装和卸载事件,然后从Service( i.e IntentService)广播接收器开始onReceive以显示新的通知包已添加。

在Manifest.xml中:

<receiver android:name=".PackageReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PACKAGE_INSTALL" />
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <data android:scheme="package"/>
        </intent-filter>
    </receiver>
PackageReceiver中的

public class PackageReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
       if (intent.getAction().equals(Intent.PACKAGE_INSTALL)) {
             //START YOUR SERVICE HERE
        } 
    }

}

或者您也可以在服务中动态注册接收器

br = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //SHOW notification here or Start Notification Service
        }
    };
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
    intentFilter.addDataScheme("package");
    registerReceiver(br, intentFilter);