好的,这是我的最终代码,如果它可以提供帮助,感谢 Egor。
注意:有两种解决方案可以强制停止玩家活动:
- 使用
startActivityForResult(intent, rq)
/finishActivity(rq)
- 使用
FLAG_ACTIVITY_CLEAR_TOP
小心使用finishActivity()
,一些外部应用程序不会因为它们的行为而关闭。对我来说,当我使用 VLC 播放器打开视频时它运行良好,但当我使用 Dailymotion 应用程序打开视频时它不起作用。
ActivityThatLaunchesPlayer.java
public class ActivityThatLaunchesPlayer extends Activity
{
private BroadcastReceiver brdreceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("broadcast signal received");
//either
finishActivity(57); //57 is my arbitrary requestcode
//or either :
Intent intentback = new Intent(getApplicationContext(), ActivityThatLaunchesPlayer.class);
intentback.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intentback);
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//set the brdcstreceiver to listen to the slot
getApplicationContext().registerReceiver(brdreceiver, new IntentFilter("com.example.portail10.timeElapsed"));
//here we launch the player (android opens a new appropriate activity)
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse(uri));
startActivityForResult(intent, 57); //again arbitrary rqstcode
//here we start the service that watch the time elapsed watching the video
intentServ = new Intent(this, TimeWatcher.class);
startService(intentServ);
}
}
TimeWatcher.java
public class TimeWatcher extends Service
{
//... some code is missing, but the main idea is here
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
//send the broadcast when time's up
Intent intentbrd = new Intent();
intentbrd.setAction("com.example.portail10.timeElapsed");
sendBroadcast(intentbrd);
System.out.println("Brdcast sent");
stopSelf();
}
}, 0, 600000); //in ms = 10min
return START_NOT_STICKY;
}