3

我想在添加新包时显示通知。我找到了清单文件需要的代码!我不知道如何在我的服务中捕捉广播。我怎样才能做到这一点?

4

1 回答 1

6

您可以注册一个接收器来接收包安装PACKAGE_INSTALLPACKAGE_ADDED卸载事件,然后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);
于 2012-07-15T05:20:07.700 回答