我想在安装我的应用程序时发出声音。我通过在我的应用程序中使用广播接收器来尝试这个。在广播接收器中,我正在运行服务以启动媒体播放器。但是我无法进入广播接收器的接收方法。但如果我尝试安装另一个应用程序,我会收到该事件。如何仅在我的应用程序中获取事件。我在清单文件中的权限
<uses-permission android:name = "android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
<receiver android:name=".DemoReceiver" >
<intent-filter >
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<action android:name="android.intent.action.USER_PRESENT"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
并在广播接收器中
import android.content.BroadcastReceiver;
导入android.content.Context;导入android.content.Intent;
public class DemoReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent bootintent) {
System.out.println("entered broadcast receiver");
if(bootintent.getAction() != null)
{
context.startService(new Intent(context, DemoService.class));
}
}
}
服务是
public class DemoService extends Service {
MediaPlayer player;
private class LogTask extends TimerTask {
public void run() {
Log.i(LOGTAG, "scheduled");
}
}
private LogTask mLogTask;
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.v("StartServiceAtBoot", "StartAtBootService Created");
player=MediaPlayer.create(this, R.raw.sirensound);
player.setLooping(false);
}
public void onStart(Intent intent, int flags, int startId) {
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
player.start();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v("StartServiceAtBoot", "StartAtBootService Destroyed");
}
}