广播接收器在安装特定应用程序后获取Toast

时间:2018-01-05 10:16:14

标签: java android

我正在使用Android应用。首先,我不熟悉BroadcastReceiver。我需要创建一个应用程序,如果安装应用程序有像“com.whatsapp”这样的特定包,广播接收器将显示Toast

public class PackageAddedReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Package Installed: ", Toast.LENGTH_LONG).show();
    }
}

清单

<receiver android:name=".receiver.PackageAddedReceiver" android:label="Package added Receiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <action android:name="android.intent.action.PACKAGE_REMOVED"/>
        <data android:scheme="package"/>
    </intent-filter>
</receiver>

如何为特定包添加BroadcastReceiver

3 个答案:

答案 0 :(得分:3)

试试这个

public class PackageAddedReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {



        Uri data = intent.getData();
        String mypkg="package:com.pck.name";

        Log.e("DATA",data+"");
        Log.e( "Action: " ,intent.getAction());

        if(mypkg.equals(data.toString())){
            Toast.makeText(context, "Package Installed: ", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(context, "not match ", Toast.LENGTH_LONG).show();
        }

    }

清单代码

 <receiver android:name=".PackageAddedReceiver">
        <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>

答案 1 :(得分:1)

一个。创建BroadcastReceiver类(实现onReceive):您可以提取与包

相关的数据
import android.content.*;
import android.net.Uri;
import android.util.Log;

public class PackageChangeReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context ctx, Intent intent) {
     Uri data = intent.getData();
     Log.d(TAG, "Action: " + intent.getAction());
     Log.d(TAG, "The DATA: " + data);
   }
}

B中。在AndroidManifest.xml中使用intent-filter声明接收器:

<receiver android:name="PackageChangeReceiver">
    <intent-filter>
     <action android:name="android.intent.action.PACKAGE_ADDED"/>
     <action android:name="android.intent.action.PACKAGE_REPLACED"/>
     <action android:name="android.intent.action.PACKAGE_REMOVED"/>
     <data android:scheme="package"/>
  </intent-filter>
</receiver> 

答案 2 :(得分:0)

接收方应按以下方式注册:

val packageAddedReceiver = PackageAddedReceiver()
    val intentFilter = IntentFilter()
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
    intentFilter.addAction(Intent.ACTION_PACKAGE_FIRST_LAUNCH)
    intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL)
    intentFilter.addDataScheme("package")
    registerReceiver(packageAddedReceiver, intentFilter)

有关进一步说明,请在链接中查看CommonsWare的答案 Can't receive broadcasts for PACKAGE intents