1

我想做的很简单:我的应用程序让用户观看最多 10 分钟的视频,然后它停止视频并返回到我的应用程序(之前的活动)。该视频显示在带有该代码的外部播放器中:

Intent intentVideo = new Intent();
intentVideo.setAction(Intent.ACTION_VIEW);
intentVideo.setData(Uri.parse(url)));
startActivity(intentVideo); 

Service然后,如果时间已过,则定期进行背景检查。

我的服务如何终止视频活动(我无法添加代码或侦听器或其他任何内容,因为它是由外部应用程序提供的)并在时间过去后让我的应用程序恢复到以前的活动?

谢谢

4

2 回答 2

1

好的,这是我的最终代码,如果它可以提供帮助,感谢 Egor。

注意:有两种解决方案可以强制停止玩家活动:

  1. 使用startActivityForResult(intent, rq)/finishActivity(rq)
  2. 使用 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;
} 
于 2013-04-15T11:49:24.117 回答
1

解决此问题的一种方法是BroadcastReceiverActivity. 当Service需要通知Activity时间到时,发送广播并在BroadcastReceiver. 然后,在里面onReceive()调用finish()Activity杀了它。希望这可以帮助。

于 2013-04-12T13:57:04.200 回答