我有一个动态的viewpager,可以显示图像,youtube视频和soundcloud音频。我添加了timertask来每3秒自动更改一次viewpager页面。我想在播放YouTube视频或播放声音云时播放视频时停止此自动更改,然后在播放停止时恢复播放。为此,我制作了两种方法starttime()
和stoptime()
。但是当我点击按钮在适配器内播放youtube视频(对于viewpager)时,我得到 RuntimeException 。
// Activity
public class Event_Details_Activity extends FragmentActivity implements RideRequestButtonCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> {
private static int currentPage = 0;
private static int NUM_PAGES = 0;
Handler myhandler;
TimerTask timerTask;
@Override
protected void onPause() {
super.onPause();
try {
pagerAdapter.displayYoutubeVideo.clearView();
pagerAdapter.displayYoutubeVideo.freeMemory();
pagerAdapter.displayYoutubeVideo.removeAllViews();
pagerAdapter.displayYoutubeVideo.destroy();
Class.forName("android.webkit.WebView")
.getMethod("onPause", (Class[]) null)
.invoke(pagerAdapter.displayYoutubeVideo, (Object[]) null);
pagerAdapter.displayYoutubeVideo.onPause();
if (handler!= null) {
handler.removeCallbacks(runnable);
}
stoptime();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void onStop() {
super.onStop();
try {
if(pagerAdapter.displayYoutubeVideo!=null){
Class.forName("android.webkit.WebView")
.getMethod("onPause", (Class[]) null)
.invoke(pagerAdapter.displayYoutubeVideo, (Object[]) null);
}
} catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch(NoSuchMethodException nsme) {
nsme.printStackTrace();
} catch(InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (pagerAdapter.mPlayer != null) {
pagerAdapter.mPlayer.release();
pagerAdapter.mPlayer = null;
}
try {
//pagerAdapter.displayYoutubeVideo.onFinishTemporaryDetach();
}catch (Exception e){
e.printStackTrace();
}
}
EventMoreDetails evDetails;
static ViewPager myPager;
ArrayList<ProdictDetailImageModel> algalary = new ArrayList<ProdictDetailImageModel>();
static ProductDetailImagePagerAdapter pagerAdapter;
LinearLayout llindicator;
LinearLayout pbloaderll;
ImageView ivrightarrow;
ImageView ivleftarrow;
TextView tvpagetext;
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
starttime();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.event_details_activity);
eventtitletv = (TextView) findViewById(R.id.eventtitletv);
locationtv = (TextView) findViewById(R.id.locationtv);
venuetv = (TextView) findViewById(R.id.venuetv);
datetv = (TextView) findViewById(R.id.datetv);
timetv = (TextView) findViewById(R.id.timetv);
pricetv = (TextView) findViewById(R.id.pricetv);
descriptiontv = (TextView) findViewById(R.id.descriptiontv);
fbshareiv = (LinearLayout) findViewById(R.id.fbshareiv);
twittershareiv = (ImageView) findViewById(R.id.twittershareiv);
yahooshareiv = (ImageView) findViewById(R.id.yahooshareiv);
nevigationll = (LinearLayout) findViewById(R.id.nevigationll);
diariseiv = (LinearLayout)findViewById(R.id.diariseiv);
birthdaydescriptiontv = (TextView)findViewById(R.id.birthdaydescriptiontv);
callpromterll = (Button) findViewById(R.id.btncallpromter);
guestlistll = (Button) findViewById(R.id.btnguestlist);
pbloaderll = (LinearLayout) findViewById(R.id.pbloaderll);
myPager = (ViewPager) findViewById(R.id.pager);
llindicator = (LinearLayout)findViewById(R.id.llindicator);
tvpagetext = (TextView) findViewById(R.id.tvpagetext);
bookticketbt = (Button) findViewById(R.id.bookticketbt);
Event_Details_Activity_Static = this;
sharell = (LinearLayout) findViewById(R.id.sharell);
Bundle bundle = getIntent().getExtras();
product_id = bundle.getString("product_id");
pattern = Pattern.compile(EMAIL_PATTERN);
menull = (LinearLayout) findViewById(R.id.menull);
ImageView menubutton = (ImageView) findViewById(R.id.menubutton);
ImageView chatAdminchiv = (ImageView) findViewById(R.id.chatAdminchiv);
RideRequestButton blackButton = (RideRequestButton) findViewById(R.id.uber_button_white);
chatAdminchiv.setVisibility(View.GONE);
blackButton.setVisibility(View.GONE);
menubutton.setVisibility(View.GONE);
ImageView youtubebutton = (ImageView) findViewById(R.id.youtubechiv);
youtubebutton.setVisibility(View.GONE);
myPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
tvpagetext.setText(arg0+1 +" of "+ pagerAdapter.getCount());
MyPagerPosition = arg0;
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
GeneralAsynctask gAsync = new GeneralAsynctask(
Event_Details_Activity.this) {
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONArray resultArray = jObj.getJSONArray("EventsList");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject jinnerObj = resultArray.getJSONObject(i);
JSONArray galary = jinnerObj.getJSONArray("gallery");
for (int j = 0; j < galary.length(); j++) {
Log.d("IMAGE lINK",galary.getString(j));
algalary.add(new ProdictDetailImageModel(galary.getString(j), ProdictDetailImageModel.TYPE_IMAGE));
}
//algalary.add(new ProdictDetailImageModel(jinnerObj.getString("video"), ProdictDetailImageModel.TYPE_VIDEO));
//algalary.add(new ProdictDetailImageModel("http://img.youtube.com/vi/"+jinnerObj.getString("video")+"/0.jpg", ProdictDetailImageModel.TYPE_VIDEO));
if(!jinnerObj.getString("video").isEmpty() && jinnerObj.getString("video")!=null){;
algalary.add(new ProdictDetailImageModel(jinnerObj.getString("video"), ProdictDetailImageModel.TYPE_VIDEO));
}
if(!jinnerObj.getString("soundcloud").isEmpty() && jinnerObj.getString("soundcloud")!=null){
ProdictDetailImageModel audio = new ProdictDetailImageModel(jinnerObj.getString("soundcloud_image"), ProdictDetailImageModel.TYPE_AUDUIO);
audio.audio = jinnerObj.getString("soundcloud");
algalary.add(audio);
}
if(algalary.size()>0){
pagerAdapter = new ProductDetailImagePagerAdapter(Event_Details_Activity.this, algalary, pbloaderll);
myPager.setAdapter(pagerAdapter);
myPager.setCurrentItem(0);
tvpagetext.setText(1 + " of " + pagerAdapter.getCount());
starttime();
}
Log.d("imagelength", algalary.size() +"");
registerReceiver(pushreceiver, new IntentFilter("com.sam"));
} // End of onCreate
public void starttime(){
Timer swipeTimer = new Timer();
NUM_PAGES = algalary.size();
handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
myPager.setCurrentItem(currentPage++, true);
}
};
timerTask = new TimerTask() {
@Override
public void run() {
handler.post(Update);
}
};
swipeTimer.schedule(timerTask, 3000, 3000);
}
public void stoptime(){
if(timerTask!=null){
timerTask.cancel();
}
}
private BroadcastReceiver pushreceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString("message");
System.out.println("STATE"+" "+state);
if(state.equals("start")){
starttime();
}else if(state.equals("stop")){
stoptime();
}
}
}
};
static int MyPagerPosition=0;
public static Handler handler = new Handler();
public static Runnable runnable = new Runnable() {
public void run() {
if( MyPagerPosition >= pagerAdapter.getCount()-1){
MyPagerPosition = 0;
}else{
MyPagerPosition = MyPagerPosition+1;
}
myPager.setCurrentItem(MyPagerPosition, true);
handler.postDelayed(runnable, 10000);
}
};
}
// ViewPager Adapter
public class ProductDetailImagePagerAdapter extends PagerAdapter{
private Activity activity;
private LayoutInflater mInflater,mLayoutInflater;
private ArrayList<ProdictDetailImageModel> ICONS;
public static final String DEVELOPER_KEY = "AIzaSyDA3eXyi3tXfHkhiNSyFm11mp4s9f9nhnk";
public static String YOUTUBE_VIDEO_CODE = "v99W1n9BSlc";
private static final int RECOVERY_DIALOG_REQUEST = 1;
public static MediaPlayer mPlayer;
public boolean isplayung = false;
public boolean ispaused = false;
AsyncTask<Void, Void, Void> prepareMusicAsync;
LinearLayout pbloaderll;
ProgressDialog pdcms;
String stream_url;
public WebView displayYoutubeVideo;
public ImageView ivaudio;
public ProductDetailImagePagerAdapter(Activity activity, ArrayList<ProdictDetailImageModel> ICONS, LinearLayout pbloaderll) {
this.activity = activity;
this.ICONS = ICONS;
mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.pbloaderll = pbloaderll;
}
@Override
public int getCount() {
return ICONS.size();
}
@Override
public Object instantiateItem(View container, final int position) {
View view = null;
if(ICONS.get(position).type.equals(ProdictDetailImageModel.TYPE_IMAGE)){
view = mInflater.inflate(R.layout.product_detail_image_row, null);
ImageView ivimage = (ImageView)view.findViewById(R.id.ivimage);
String eventImageLink = ICONS.get(position).image;
if (!eventImageLink.equals("")) {
try {
String apiLink = eventImageLink;
String encodedurl = "";
encodedurl = apiLink.substring(0,apiLink.lastIndexOf('/'))+ "/"+ Uri.encode(apiLink.substring(
apiLink.lastIndexOf('/') + 1));
Log.d("IMAGE LINK", "encodedurl:"+encodedurl);
if (!apiLink.equals("") && apiLink != null) {
Picasso.with(activity)
.load(encodedurl)
.placeholder(R.drawable.listviewbg)
.error(R.drawable.listviewbg)
.into(ivimage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}else if(ICONS.get(position).type.equals(ProdictDetailImageModel.TYPE_VIDEO)){
view = mInflater.inflate(R.layout.product_detail_video_image_row, null);
ImageView ivimage = (ImageView)view.findViewById(R.id.ivimage);
ImageView play = (ImageView)view.findViewById(R.id.play);
String eventImageLink = "http://img.youtube.com/vi/"+ICONS.get(position).image+"/0.jpg";
if (!eventImageLink.equals("")) {
try {
String apiLink = eventImageLink;
String encodedurl = "";
encodedurl = apiLink.substring(0,apiLink.lastIndexOf('/'))+ "/"+ Uri.encode(apiLink.substring(
apiLink.lastIndexOf('/') + 1));
Log.d("IMAGE LINK", "encodedurl:"+encodedurl);
if (!apiLink.equals("") && apiLink != null) {
Picasso.with(activity)
.load(encodedurl) // load: This path may be a remote URL,
.placeholder(R.drawable.listviewbg)
.error(R.drawable.listviewbg)
.into(ivimage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(activity, YoutubePlayerActivity.class);
i.putExtra("youtubeid", YOUTUBE_VIDEO_CODE);
activity.startActivity(i);
}
});
YOUTUBE_VIDEO_CODE = ICONS.get(position).image;
}else{
view = mInflater.inflate(R.layout.product_detail_audio_image_row, null);
ImageView ivimage = (ImageView)view.findViewById(R.id.ivimage);
ivaudio = (ImageView)view.findViewById(R.id.ivaudio);
String eventImageLink = ICONS.get(position).image;
if (!eventImageLink.equals("")) {
try {
String apiLink = eventImageLink;
String encodedurl = "";
encodedurl = apiLink.substring(0,apiLink.lastIndexOf('/'))+ "/"+ Uri.encode(apiLink.substring(
apiLink.lastIndexOf('/') + 1));
Log.d("IMAGE LINK", "encodedurl:"+encodedurl);
if (!apiLink.equals("") && apiLink != null) {
Picasso.with(activity)
.load(encodedurl)
.placeholder(R.drawable.listviewbg)
.error(R.drawable.listviewbg)
.into(ivimage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
ivaudio.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
if (Event_Details_Activity.handler!= null) {
Event_Details_Activity.handler.removeCallbacks(Event_Details_Activity.runnable);
}
}catch (Exception e){
e.printStackTrace();
}
Log.v("IS PLAYING >", isplayung +"");
if(!isplayung) {
stream_url = replaceString(ICONS.get(position).audio);
Log.e("stream_url","***"+stream_url);
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
Log.v("Stream Url >", stream_url + "?client_id=fd557f1b3b255669587932f72b65f562");
mPlayer.setDataSource(stream_url + "?client_id=fd557f1b3b255669587932f72b65f562");
} catch (IllegalArgumentException e) {
Toast.makeText(activity, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(activity, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(activity, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
commentpostActivity(pbloaderll);
isplayung = true;
ivaudio.setImageResource(R.drawable.audio_pause);
}else{
if(mPlayer!=null && mPlayer.isPlaying() && !ispaused){
mPlayer.pause();
ispaused = true;
ivaudio.setImageResource(R.drawable.audio_play);
}else if(mPlayer!=null && ispaused){
mPlayer.start();
ispaused = false;
ivaudio.setImageResource(R.drawable.audio_pause);
}
}
}
});
}
((ViewPager) container).addView(view, 0);
return view;
}
@Override
public float getPageWidth(int position) {
return(1f);
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
private static class ViewHolder {
RelativeLayout linearLayout;
ImageView cover;
TextView title;
TextView pricetv;
TextView destaince;;
}
public String replaceString(String rtstr) {
rtstr = rtstr.replace("[", "");
rtstr = rtstr.replace("{", "");
rtstr = rtstr.replace("}", "");
rtstr = rtstr.replace("\"", "");
rtstr = rtstr.replace("\\/", "/");
rtstr = rtstr.replace("]", "");
rtstr = rtstr.replace(" ", "%20");
return rtstr;
}
void commentpostActivity(final LinearLayout pbloaderll){
prepareMusicAsync = new AsyncTask<Void, Void, Void>( ){
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(activity, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(activity, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mPlayer.start();
pbloaderll.setVisibility(View.GONE);
}
};
prepareMusicAsync.execute( );
}
Dialog youtubevideodialog;
private void showWaitingnooftickitsDialog() {
try {
youtubevideodialog = new Dialog(activity);
youtubevideodialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
youtubevideodialog.setContentView(R.layout.product_detail_video_row);
youtubevideodialog.setCancelable(true);
youtubevideodialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
YouTubePlayerView youTubeView = (YouTubePlayerView)youtubevideodialog.findViewById(R.id.youtubeplayer);
youtubevideodialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// LOGCAT
FATAL EXCEPTION: main
Process: com.nits.londonclubnights, PID: 11899
java.lang.RuntimeException: Unable to resume activity {com.nits.londonclubnights/com.nits.londonclubnights.YoutubePlayerActivity}: java.lang.ClassCastException: com.nits.application.AppApplication cannot be cast to com.nits.londonclubnights.Event_Details_Activity
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3028)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3063)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.ClassCastException: com.nits.application.AppApplication cannot be cast to com.nits.londonclubnights.Event_Details_Activity
at com.nits.londonclubnights.YoutubePlayerActivity.onResume(YoutubePlayerActivity.java:110)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1280)
at android.app.Activity.performResume(Activity.java:6096)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3011)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3063)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
// YoutubeBaseActivity
public class YoutubePlayerActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "AIzaSyDA3eXyi3tXfHkhiNSyFm11mp4s9f9nhnk";
// YouTube video id
public static String YOUTUBE_VIDEO_CODE = "v99W1n9BSlc";
private static final int RECOVERY_DIALOG_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_youtube_player);
this.setFinishOnTouchOutside(true);
YouTubePlayerView youTubeView = (YouTubePlayerView)findViewById(R.id.youtubeplayer);
youTubeView.initialize(DEVELOPER_KEY, this);
YOUTUBE_VIDEO_CODE = getIntent().getExtras().getString("youtubeid");
Log.e("YOUTUBE_VIDEO_CODE",":"+YOUTUBE_VIDEO_CODE);
try {
if(Event_Details_Activity.pagerAdapter.mPlayer!=null && Event_Details_Activity.pagerAdapter.mPlayer.isPlaying() && !Event_Details_Activity.pagerAdapter.ispaused){
Event_Details_Activity.pagerAdapter.mPlayer.pause();
Event_Details_Activity.pagerAdapter.ispaused = true;
Event_Details_Activity.pagerAdapter.ivaudio.setImageResource(R.drawable.audio_play);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
Intent intent1 = new Intent("com.sam");
intent1.putExtra("message", "stop");
YoutubePlayerActivity.this.sendBroadcast(intent1);
}
@Override
protected void onPause() {
super.onPause();
Intent intent2 = new Intent("com.sam");
intent2.putExtra("message", "start");
YoutubePlayerActivity.this.sendBroadcast(intent2);
}
}
答案 0 :(得分:0)
不要从其他活动中调用Event_Details_Activity
类中的方法。
在BroadCastReciever
和Event_Details_Activity
方法调用onRecieve
和starttime()
方法中创建stoptime()
。
因此,只要您希望从starttime()
外部拨打stoptime()
和Event_Details_Activity
,就可以发送广播。
**还有很多其他方法可以做到这一点。您可以谷歌并选择最佳方式。