Android Issues
getWidth() and getHeight return zero after onMeasure() (specific devices) Use getMeasuredWidth/Height() here. getWidth/Height() aren’t valid until after a layout.
getWidth() and getHeight return zero after onMeasure() (specific devices) Use getMeasuredWidth/Height() here. getWidth/Height() aren’t valid until after a layout.
1 2 3 4 5 6 7 8 |
<ImageView android:id="@+id/postFeature" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:adjustViewBounds="true" android:scaleType="fitCenter" android:src="@drawable/be_flawless_category" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class MyURLClass { public String addOrChangeQuery(String mainUrl, String key, String newValue) throws MalformedURLException, UnsupportedEncodingException { int queryStart = mainUrl.indexOf('?'); String newUrl; if (queryStart == -1) { newUrl = mainUrl + "?" + getNewQuery(null, key, newValue); } else { newUrl = mainUrl.substring(0, queryStart) + "?" + getNewQuery(mainUrl.substring(queryStart + 1), key, newValue); } return newUrl; } private String getNewQuery(String query, String key, String newValue) throws UnsupportedEncodingException { Map<String, String> map = new HashMap<>(); if (query == null) { map.put(key, newValue); } else { String[] params = query.split("&"); Boolean isKey = false; for (String param : params) { String queryName = param.split("=")[0]; String queryValue = param.split("=")[1]; if (queryName.equalsIgnoreCase(key)) { isKey = true; queryValue = newValue; } map.put(queryName, queryValue); } if (!isKey) { map.put(key, newValue); } } StringBuilder sb = new StringBuilder(); for (HashMap.Entry<String, String> e : map.entrySet()) { if (sb.length() > 0) { sb.append('&'); } sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8")); } return sb.toString(); } private Map<String, String> getQueryMap(String query) { Map<String, String> map = new HashMap<>(); String[] params = query.split("&"); for (String param : params) { String queryName = param.split("=")[0]; String queryValue = param.split("=")[1]; map.put(queryName, queryValue); } return map; } } |
You can’t increase the heap size dynamically but you can request to use more by using. android:largeHeap=”true” in the manifest.xml,you can add in your manifest these lines it is working for some situations.
1 2 3 4 5 6 7 |
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:largeHeap="true" android:supportsRtl="true" android:theme="@style/AppTheme"> |
Whether your application’s processes should be created with a large Dalvik heap. This applies to all processes created for the […]
The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.
1 2 3 4 5 6 |
private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } |
You will also need:
1 |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
in […]
In this tutorial we’ll discuss and implement a very important component of the Android Framework named BroadcastReceiver. Android BroadcastReceiver Overview A BroadcastReceiver is a dormant component of Android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification […]
File : AndroidMainifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="UTF-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.swipe" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <activity android:name="com.androidexample.swipescreen.SwipeScreenExample" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
File : src/SwipeScreenExample.java Create touch event with the use of SimpleGestureFilter class object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.Toast; import com.androidexample.swipescreen.SimpleGestureFilter.SimpleGestureListener; public class SwipeScreenExample extends Activity implements SimpleGestureListener { private SimpleGestureFilter detector; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.swipe_screen); // Detect touched area detector = new SimpleGestureFilter(this, this); } @Override public boolean dispatchTouchEvent(MotionEvent me) { // Call onTouchEvent of SimpleGestureFilter class this.detector.onTouchEvent(me); return super.dispatchTouchEvent(me); } @Override public void onSwipe(int direction) { String str = ""; switch (direction) { case SimpleGestureFilter.SWIPE_RIGHT: str = "Swipe Right"; break; case SimpleGestureFilter.SWIPE_LEFT: str = "Swipe Left"; break; case SimpleGestureFilter.SWIPE_DOWN: str = "Swipe Down"; break; case SimpleGestureFilter.SWIPE_UP: str = "Swipe Up"; break; } Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } @Override public void onDoubleTap() { Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show(); } |
File : src/SimpleGestureFilter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
import android.app.Activity; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; public class SimpleGestureFilter extends SimpleOnGestureListener { public final static int SWIPE_UP = 1; public final static int SWIPE_DOWN = 2; public final static int SWIPE_LEFT = 3; public final static int SWIPE_RIGHT = 4; public final static int MODE_TRANSPARENT = 0; public final static int MODE_SOLID = 1; public final static int MODE_DYNAMIC = 2; private final static int ACTION_FAKE = -13; //just an unlikely number private int swipe_Min_Distance = 100; private int swipe_Max_Distance = 350; private int swipe_Min_Velocity = 100; private int mode = MODE_DYNAMIC; private boolean running = true; private boolean tapIndicator = false; private Activity context; private GestureDetector detector; private SimpleGestureListener listener; public SimpleGestureFilter(Activity context, SimpleGestureListener sgl) { this.context = context; this.detector = new GestureDetector(context, this); this.listener = sgl; } public void onTouchEvent(MotionEvent event) { if (!this.running) return; boolean result = this.detector.onTouchEvent(event); if (this.mode == MODE_SOLID) event.setAction(MotionEvent.ACTION_CANCEL); else if (this.mode == MODE_DYNAMIC) { if (event.getAction() == ACTION_FAKE) event.setAction(MotionEvent.ACTION_UP); else if (result) event.setAction(MotionEvent.ACTION_CANCEL); else if (this.tapIndicator) { event.setAction(MotionEvent.ACTION_DOWN); this.tapIndicator = false; } } //else just do nothing, it's Transparent } public int getMode() { return this.mode; } public void setMode(int m) { this.mode = m; } public void setEnabled(boolean status) { this.running = status; } public int getSwipeMaxDistance() { return this.swipe_Max_Distance; } public void setSwipeMaxDistance(int distance) { this.swipe_Max_Distance = distance; } public int getSwipeMinDistance() { return this.swipe_Min_Distance; } public void setSwipeMinDistance(int distance) { this.swipe_Min_Distance = distance; } public int getSwipeMinVelocity() { return this.swipe_Min_Velocity; } public void setSwipeMinVelocity(int distance) { this.swipe_Min_Velocity = distance; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { final float xDistance = Math.abs(e1.getX() - e2.getX()); final float yDistance = Math.abs(e1.getY() - e2.getY()); if (xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance) return false; velocityX = Math.abs(velocityX); velocityY = Math.abs(velocityY); boolean result = false; if (velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance) { if (e1.getX() > e2.getX()) // right to left this.listener.onSwipe(SWIPE_LEFT); else this.listener.onSwipe(SWIPE_RIGHT); result = true; } else if (velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance) { if (e1.getY() > e2.getY()) // bottom to up this.listener.onSwipe(SWIPE_UP); else this.listener.onSwipe(SWIPE_DOWN); result = true; } return result; } @Override public boolean onSingleTapUp(MotionEvent e) { this.tapIndicator = true; return false; } @Override public boolean onDoubleTap(MotionEvent arg) { this.listener.onDoubleTap(); return true; } @Override public boolean onDoubleTapEvent(MotionEvent arg) { return true; } @Override public boolean onSingleTapConfirmed(MotionEvent arg) { if (this.mode == MODE_DYNAMIC) { // we owe an ACTION_UP, so we fake an arg.setAction(ACTION_FAKE); //action which will be converted to an ACTION_UP later. this.context.dispatchTouchEvent(arg); } return false; } static interface SimpleGestureListener { void onSwipe(int direction); void onDoubleTap(); } } |
media_controller.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#CC000000" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" android:paddingTop="4dip"> <ImageButton android:id="@+id/prev" style="@android:style/MediaButton.Previous" android:contentDescription="@string/media_controls" /> <ImageButton android:id="@+id/rew" style="@android:style/MediaButton.Rew" android:contentDescription="@string/media_controls" /> <ImageButton android:id="@+id/pause" style="@android:style/MediaButton.Play" android:contentDescription="@string/media_controls" /> <ImageButton android:id="@+id/ffwd" style="@android:style/MediaButton.Ffwd" android:contentDescription="@string/media_controls" /> <ImageButton android:id="@+id/next" style="@android:style/MediaButton.Next" android:contentDescription="@string/media_controls" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/time_current" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:paddingLeft="4dip" android:paddingRight="4dip" android:paddingTop="4dip" android:textColor="@android:color/white" android:textSize="14sp" android:textStyle="bold" /> <SeekBar android:id="@+id/mediacontroller_progress" style="?android:attr/progressBarStyleHorizontal" android:layout_width="0dip" android:layout_height="32dip" android:layout_weight="1" /> <TextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:paddingLeft="4dip" android:paddingRight="4dip" android:paddingTop="4dip" android:textColor="@android:color/white" android:textSize="14sp" android:textStyle="bold" /> <ImageButton android:id="@+id/fullscreen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" android:layout_marginTop="-7dp" android:background="@android:color/transparent" android:contentDescription="@string/media_controls" android:paddingBottom="4dip" android:paddingLeft="10dip" android:paddingRight="4dip" android:paddingTop="4dip" /> </LinearLayout> </LinearLayout> |
activity_video_player.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/video_container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black" android:gravity="center_horizontal|center_vertical" android:orientation="vertical"> <FrameLayout android:id="@+id/videoSurfaceContainer" android:layout_width="match_parent" android:layout_height="wrap_content"> <SurfaceView android:id="@+id/videoSurface" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout> </LinearLayout> |
VideoControllerView.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 |
package com.shubham.chiquis.activity; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.shubham.chiquis.R; import java.lang.ref.WeakReference; import java.util.Formatter; import java.util.Locale; /** * A view containing controls for a MediaPlayer. Typically contains the * buttons like "Play/Pause", "Rewind", "Fast Forward" and a progress * slider. It takes care of synchronizing the controls with the state * of the MediaPlayer. * <p> * The way to use this class is to instantiate it programatically. * The MediaController will create a default set of controls * and put them in a window floating above your application. Specifically, * the controls will float above the view specified with setAnchorView(). * The window will disappear if left idle for three seconds and reappear * when the user touches the anchor view. * <p> * Functions like show() and hide() have no effect when MediaController * is created in an xml layout. * <p> * MediaController will hide and * show the buttons according to these rules: * <ul> * <li> The "previous" and "next" buttons are hidden until setPrevNextListeners() * has been called * <li> The "previous" and "next" buttons are visible but disabled if * setPrevNextListeners() was called with null listeners * <li> The "rewind" and "fastforward" buttons are shown unless requested * otherwise by using the MediaController(Context, boolean) constructor * with the boolean set to false * </ul> */ public class VideoControllerView extends FrameLayout { private static final String TAG = "VideoControllerView"; private static final int sDefaultTimeout = 3000; private static final int FADE_OUT = 1; private static final int SHOW_PROGRESS = 2; StringBuilder mFormatBuilder; Formatter mFormatter; private MediaPlayerControl mPlayer; private Context mContext; private ViewGroup mAnchor; private View mRoot; private ProgressBar mProgress; private TextView mEndTime, mCurrentTime; private boolean mShowing; private boolean mDragging; private boolean mUseFastForward; private boolean mFromXml; private boolean mListenersSet; private View.OnClickListener mNextListener, mPrevListener; private ImageButton mPauseButton; private ImageButton mFfwdButton; private ImageButton mRewButton; private ImageButton mNextButton; private ImageButton mPrevButton; private ImageButton mFullscreenButton; private Handler mHandler = new MessageHandler(this); private View.OnClickListener mPauseListener = new View.OnClickListener() { public void onClick(View v) { doPauseResume(); show(sDefaultTimeout); } }; private View.OnClickListener mFullscreenListener = new View.OnClickListener() { public void onClick(View v) { doToggleFullscreen(); show(sDefaultTimeout); } }; // There are two scenarios that can trigger the seekbar listener to trigger: // // The first is the user using the touchpad to adjust the posititon of the // seekbar's thumb. In this case onStartTrackingTouch is called followed by // a number of onProgressChanged notifications, concluded by onStopTrackingTouch. // We're setting the field "mDragging" to true for the duration of the dragging // session to avoid jumps in the position in case of ongoing playback. // // The second scenario involves the user operating the scroll ball, in this // case there WON'T BE onStartTrackingTouch/onStopTrackingTouch notifications, // we will simply apply the updated position without suspending regular updates. private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() { public void onStartTrackingTouch(SeekBar bar) { show(3600000); mDragging = true; // By removing these pending progress messages we make sure // that a) we won't update the progress while the user adjusts // the seekbar and b) once the user is done dragging the thumb // we will post one of these messages to the queue again and // this ensures that there will be exactly one message queued up. mHandler.removeMessages(SHOW_PROGRESS); } public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) { if (mPlayer == null) { return; } if (!fromuser) { // We're not interested in programmatically generated changes to // the progress bar's position. return; } long duration = mPlayer.getDuration(); long newposition = (duration * progress) / 1000L; mPlayer.seekTo((int) newposition); if (mCurrentTime != null) mCurrentTime.setText(stringForTime((int) newposition)); } public void onStopTrackingTouch(SeekBar bar) { mDragging = false; setProgress(); updatePausePlay(); show(sDefaultTimeout); // Ensure that progress is properly updated in the future, // the call to show() does not guarantee this because it is a // no-op if we are already showing. mHandler.sendEmptyMessage(SHOW_PROGRESS); } }; private View.OnClickListener mRewListener = new View.OnClickListener() { public void onClick(View v) { if (mPlayer == null) { return; } int pos = mPlayer.getCurrentPosition(); pos -= 5000; // milliseconds mPlayer.seekTo(pos); setProgress(); show(sDefaultTimeout); } }; private View.OnClickListener mFfwdListener = new View.OnClickListener() { public void onClick(View v) { if (mPlayer == null) { return; } int pos = mPlayer.getCurrentPosition(); pos += 15000; // milliseconds mPlayer.seekTo(pos); setProgress(); show(sDefaultTimeout); } }; public VideoControllerView(Context context, AttributeSet attrs) { super(context, attrs); mRoot = null; mContext = context; mUseFastForward = true; mFromXml = true; Log.i(TAG, TAG); } public VideoControllerView(Context context, boolean useFastForward) { super(context); mContext = context; mUseFastForward = useFastForward; Log.i(TAG, TAG); } public VideoControllerView(Context context) { this(context, true); Log.i(TAG, TAG); } @Override public void onFinishInflate() { if (mRoot != null) initControllerView(mRoot); } public void setMediaPlayer(MediaPlayerControl player) { mPlayer = player; updatePausePlay(); updateFullScreen(); } /** * Set the view that acts as the anchor for the control view. * This can for example be a VideoView, or your Activity's main view. * * @param view The view to which to anchor the controller when it is visible. */ public void setAnchorView(ViewGroup view) { mAnchor = view; FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); removeAllViews(); View v = makeControllerView(); addView(v, frameParams); } /** * Create the view that holds the widgets that control playback. * Derived classes can override this to create their own. * * @return The controller view. * @hide This doesn't work as advertised */ protected View makeControllerView() { LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRoot = inflate.inflate(R.layout.media_controller, null); initControllerView(mRoot); return mRoot; } private void initControllerView(View v) { mPauseButton = (ImageButton) v.findViewById(R.id.pause); if (mPauseButton != null) { mPauseButton.requestFocus(); mPauseButton.setOnClickListener(mPauseListener); } mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen); if (mFullscreenButton != null) { mFullscreenButton.requestFocus(); mFullscreenButton.setOnClickListener(mFullscreenListener); } mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd); if (mFfwdButton != null) { mFfwdButton.setOnClickListener(mFfwdListener); if (!mFromXml) { mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE); } } mRewButton = (ImageButton) v.findViewById(R.id.rew); if (mRewButton != null) { mRewButton.setOnClickListener(mRewListener); if (!mFromXml) { mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE); } } // By default these are hidden. They will be enabled when setPrevNextListeners() is called mNextButton = (ImageButton) v.findViewById(R.id.next); if (mNextButton != null && !mFromXml && !mListenersSet) { mNextButton.setVisibility(View.GONE); } mPrevButton = (ImageButton) v.findViewById(R.id.prev); if (mPrevButton != null && !mFromXml && !mListenersSet) { mPrevButton.setVisibility(View.GONE); } mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress); if (mProgress != null) { if (mProgress instanceof SeekBar) { SeekBar seeker = (SeekBar) mProgress; seeker.setOnSeekBarChangeListener(mSeekListener); } mProgress.setMax(1000); } mEndTime = (TextView) v.findViewById(R.id.time); mCurrentTime = (TextView) v.findViewById(R.id.time_current); mFormatBuilder = new StringBuilder(); mFormatter = new Formatter(mFormatBuilder, Locale.getDefault()); installPrevNextListeners(); } /** * Show the controller on screen. It will go away * automatically after 3 seconds of inactivity. */ public void show() { show(sDefaultTimeout); } /** * Disable pause or seek buttons if the stream cannot be paused or seeked. * This requires the control interface to be a MediaPlayerControlExt */ private void disableUnsupportedButtons() { if (mPlayer == null) { return; } try { if (mPauseButton != null && !mPlayer.canPause()) { mPauseButton.setEnabled(false); } if (mRewButton != null && !mPlayer.canSeekBackward()) { mRewButton.setEnabled(false); } if (mFfwdButton != null && !mPlayer.canSeekForward()) { mFfwdButton.setEnabled(false); } } catch (IncompatibleClassChangeError ex) { // We were given an old version of the interface, that doesn't have // the canPause/canSeekXYZ methods. This is OK, it just means we // assume the media can be paused and seeked, and so we don't disable // the buttons. } } /** * Show the controller on screen. It will go away * automatically after 'timeout' milliseconds of inactivity. * * @param timeout The timeout in milliseconds. Use 0 to show * the controller until hide() is called. */ public void show(int timeout) { if (!mShowing && mAnchor != null) { setProgress(); if (mPauseButton != null) { mPauseButton.requestFocus(); } disableUnsupportedButtons(); FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM ); mAnchor.addView(this, tlp); mShowing = true; } updatePausePlay(); updateFullScreen(); // cause the progress bar to be updated even if mShowing // was already true. This happens, for example, if we're // paused with the progress bar showing the user hits play. mHandler.sendEmptyMessage(SHOW_PROGRESS); Message msg = mHandler.obtainMessage(FADE_OUT); if (timeout != 0) { mHandler.removeMessages(FADE_OUT); mHandler.sendMessageDelayed(msg, timeout); } } public boolean isShowing() { return mShowing; } /** * Remove the controller from the screen. */ public void hide() { if (mAnchor == null) { return; } try { mAnchor.removeView(this); mHandler.removeMessages(SHOW_PROGRESS); } catch (IllegalArgumentException ex) { Log.w("MediaController", "already removed"); } mShowing = false; } private String stringForTime(int timeMs) { int totalSeconds = timeMs / 1000; int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; mFormatBuilder.setLength(0); if (hours > 0) { return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); } else { return mFormatter.format("%02d:%02d", minutes, seconds).toString(); } } private int setProgress() { if (mPlayer == null || mDragging) { return 0; } int position = mPlayer.getCurrentPosition(); int duration = mPlayer.getDuration(); if (mProgress != null) { if (duration > 0) { // use long to avoid overflow long pos = 1000L * position / duration; mProgress.setProgress((int) pos); } int percent = mPlayer.getBufferPercentage(); mProgress.setSecondaryProgress(percent * 10); } if (mEndTime != null) mEndTime.setText(stringForTime(duration)); if (mCurrentTime != null) mCurrentTime.setText(stringForTime(position)); return position; } @Override public boolean onTouchEvent(MotionEvent event) { show(sDefaultTimeout); return true; } @Override public boolean onTrackballEvent(MotionEvent ev) { show(sDefaultTimeout); return false; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (mPlayer == null) { return true; } int keyCode = event.getKeyCode(); final boolean uniqueDown = event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN; if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE) { if (uniqueDown) { doPauseResume(); show(sDefaultTimeout); if (mPauseButton != null) { mPauseButton.requestFocus(); } } return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) { if (uniqueDown && !mPlayer.isPlaying()) { mPlayer.start(); updatePausePlay(); show(sDefaultTimeout); } return true; } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) { if (uniqueDown && mPlayer.isPlaying()) { mPlayer.pause(); updatePausePlay(); show(sDefaultTimeout); } return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) { // don't show the controls for volume adjustment return super.dispatchKeyEvent(event); } else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) { if (uniqueDown) { hide(); } return true; } show(sDefaultTimeout); return super.dispatchKeyEvent(event); } public void updatePausePlay() { if (mRoot == null || mPauseButton == null || mPlayer == null) { return; } if (mPlayer.isPlaying()) { mPauseButton.setImageResource(R.drawable.ic_media_pause); } else { mPauseButton.setImageResource(R.drawable.ic_media_play); } } public void updateFullScreen() { if (mRoot == null || mFullscreenButton == null || mPlayer == null) { return; } if (mPlayer.isFullScreen()) { mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_shrink); } else { mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_stretch); } } private void doPauseResume() { if (mPlayer == null) { return; } if (mPlayer.isPlaying()) { mPlayer.pause(); } else { mPlayer.start(); } updatePausePlay(); } private void doToggleFullscreen() { if (mPlayer == null) { return; } mPlayer.toggleFullScreen(); } @Override public void setEnabled(boolean enabled) { if (mPauseButton != null) { mPauseButton.setEnabled(enabled); } if (mFfwdButton != null) { mFfwdButton.setEnabled(enabled); } if (mRewButton != null) { mRewButton.setEnabled(enabled); } if (mNextButton != null) { mNextButton.setEnabled(enabled && mNextListener != null); } if (mPrevButton != null) { mPrevButton.setEnabled(enabled && mPrevListener != null); } if (mProgress != null) { mProgress.setEnabled(enabled); } disableUnsupportedButtons(); super.setEnabled(enabled); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(VideoControllerView.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(VideoControllerView.class.getName()); } private void installPrevNextListeners() { if (mNextButton != null) { mNextButton.setOnClickListener(mNextListener); mNextButton.setEnabled(mNextListener != null); } if (mPrevButton != null) { mPrevButton.setOnClickListener(mPrevListener); mPrevButton.setEnabled(mPrevListener != null); } } public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) { mNextListener = next; mPrevListener = prev; mListenersSet = true; if (mRoot != null) { installPrevNextListeners(); if (mNextButton != null && !mFromXml) { mNextButton.setVisibility(View.VISIBLE); } if (mPrevButton != null && !mFromXml) { mPrevButton.setVisibility(View.VISIBLE); } } } public interface MediaPlayerControl { void start(); void pause(); int getDuration(); int getCurrentPosition(); void seekTo(int pos); boolean isPlaying(); int getBufferPercentage(); boolean canPause(); boolean canSeekBackward(); boolean canSeekForward(); boolean isFullScreen(); void toggleFullScreen(); } private static class MessageHandler extends Handler { private final WeakReference<VideoControllerView> mView; MessageHandler(VideoControllerView view) { mView = new WeakReference<VideoControllerView>(view); } @Override public void handleMessage(Message msg) { VideoControllerView view = mView.get(); if (view == null || view.mPlayer == null) { return; } int pos; switch (msg.what) { case FADE_OUT: view.hide(); break; case SHOW_PROGRESS: pos = view.setProgress(); if (!view.mDragging && view.mShowing && view.mPlayer.isPlaying()) { msg = obtainMessage(SHOW_PROGRESS); sendMessageDelayed(msg, 1000 - (pos % 1000)); } break; } } } } |
VideoPlayerActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
package com.shubham.chiquis.activity; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.FrameLayout; import com.shubham.chiquis.R; import java.io.IOException; public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl { SurfaceView videoSurface; MediaPlayer player; VideoControllerView controller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_player); videoSurface = (SurfaceView) findViewById(R.id.videoSurface); SurfaceHolder videoHolder = videoSurface.getHolder(); videoHolder.addCallback(this); player = new MediaPlayer(); controller = new VideoControllerView(this); try { player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setDataSource(this, Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")); player.setOnPreparedListener(this); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean onTouchEvent(MotionEvent event) { controller.show(); return false; } // Implement SurfaceHolder.Callback @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { player.setDisplay(holder); player.prepareAsync(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } // End SurfaceHolder.Callback // Implement MediaPlayer.OnPreparedListener @Override public void onPrepared(MediaPlayer mp) { controller.setMediaPlayer(this); controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer)); player.start(); } // End MediaPlayer.OnPreparedListener // Implement VideoMediaController.MediaPlayerControl @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return true; } @Override public boolean canSeekForward() { return true; } @Override public int getBufferPercentage() { return 0; } @Override public int getCurrentPosition() { return player.getCurrentPosition(); } @Override public int getDuration() { return player.getDuration(); } @Override public boolean isPlaying() { return player.isPlaying(); } @Override public void pause() { player.pause(); } @Override public void seekTo(int i) { player.seekTo(i); } @Override public void start() { player.start(); } @Override public boolean isFullScreen() { return false; } @Override public void toggleFullScreen() { } // End VideoMediaController.MediaPlayerControl } |
Download Media Controls set permission
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
Do these modifications to your animation files: enter.xml:
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"> <translate android:duration="500" android:fromXDelta="100%" android:fromYDelta="0%" android:toXDelta="0%" android:toYDelta="0%" /> </set> |
exit.xml:
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"> <translate android:duration="500" android:fromXDelta="0%" android:fromYDelta="0%" android:toXDelta="-100%" android:toYDelta="0%" /> </set> |
You’ll have your second activity sliding in from right to the left. For a better understadnig on how to play around with the fromXDelta and toXDelta values for the animations, here is a very basic illustration on the values: This way you […]
Add google-services.json file Add file into maifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!-- Firebase Notifications --> <service android:name=".service.MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".service.MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> <!-- ./Firebase Notifications --> |
Create Files Config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Config { public static final String SHARED_PREF = "TOURING_COMPANIONS"; // global topic to receive app wide push notifications public static final String TOPIC_GLOBAL = "global"; // broadcast receiver intent filters public static final String REGISTRATION_COMPLETE = "registrationComplete"; public static final String PUSH_NOTIFICATION = "pushNotification"; // id to handle the notification in the notification tray public static final int NOTIFICATION_ID = 100; public static final int NOTIFICATION_ID_BIG_IMAGE = 101; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.touring.companions.service; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.touring.companions.utility.Config; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); @Override public void onTokenRefresh() { super.onTokenRefresh(); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); // Saving reg id to shared preferences storeRegIdInPref(refreshedToken); // sending reg id to your server sendRegistrationToServer(refreshedToken); // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); registrationComplete.putExtra("token", refreshedToken); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } private void sendRegistrationToServer(final String token) { // sending gcm token to server Log.e(TAG, "sendRegistrationToServer: " + token); } private void storeRegIdInPref(String token) { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); SharedPreferences.Editor editor = pref.edit(); editor.putString("regId", token); editor.apply(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
package com.touring.companions.service; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.touring.companions.utility.Config; import com.touring.companions.activities.MoreInfoNotification; import com.touring.companions.dbhelper.DatabaseHelper; import com.touring.companions.utility.NotificationUtils; import com.touring.companions.utility.SqliteUtil; import org.json.JSONException; import org.json.JSONObject; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); private NotificationUtils notificationUtils; @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.e(TAG, "From: " + remoteMessage.getFrom()); if (remoteMessage == null) return; // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); handleNotification(remoteMessage.getNotification().getBody()); } // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject json = new JSONObject(remoteMessage.getData().toString()); handleDataMessage(json); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } } private void handleNotification(String message) { if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); } else { // If the app is in background, firebase itself handles the notification } } private void handleDataMessage(JSONObject json) { Log.e(TAG, "push json: " + json.toString()); try { JSONObject data = json.getJSONObject("data"); String title = data.getString("title"); String message = data.getString("message"); // boolean isBackground = data.getBoolean("is_background"); String imageUrl = data.getString("image"); String timestamp = data.getString("timestamp"); // JSONObject payload = data.getJSONObject("payload"); Log.e(TAG, "title: " + title); Log.e(TAG, "message: " + message); // Log.e(TAG, "isBackground: " + isBackground); // Log.e(TAG, "payload: " + payload.toString()); Log.e(TAG, "imageUrl: " + imageUrl); // Log.e(TAG, "timestamp: " + timestamp); DatabaseHelper dataBaseHelper = new DatabaseHelper(getApplicationContext()); dataBaseHelper.insertData(title, message, timestamp); Cursor cursor = dataBaseHelper.getData(SqliteUtil.TABLE_NOTIFICATION); int idColumn = cursor.getColumnIndex("id"); int titleColumn = cursor.getColumnIndex("title"); int messageColumn = cursor.getColumnIndex("message"); cursor.moveToFirst(); // Verify that we have results if (cursor != null && (cursor.getCount() > 0)) { do { Log.d(TAG, "id " + cursor.getString(idColumn)); Log.d(TAG, "Title " + cursor.getString(titleColumn)); Log.d(TAG, "Message " + cursor.getString(messageColumn)); // Keep getting results as long as they exist } while (cursor.moveToNext()); } else { Toast.makeText(getApplicationContext(), "No Results to Show", Toast.LENGTH_SHORT).show(); } dataBaseHelper.close(); if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); } else { // app is in background, show the notification in notification tray Intent resultIntent = new Intent(getApplicationContext(), MoreInfoNotification.class); resultIntent.putExtra("message", message); // check for image attachment if (TextUtils.isEmpty(imageUrl)) { showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent); } else { // image is present, show notification with image showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl); } } } catch (JSONException e) { Log.e(TAG, "Json Exception: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } /** * Showing notification with text only */ private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent); } /** * Showing notification with text and image */ private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); } } |
In activity
1 |
private BroadcastReceiver mRegistrationBroadcastReceiver; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Override protected void onResume() { super.onResume(); // register GCM registration complete receiver LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE)); // register new push message receiver // by doing this, the activity will be notified each time a new message arrives LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION)); // clear the notification area when the app is opened NotificationUtils.clearNotifications(getApplicationContext()); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); } |
To receive Brodcast
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG,"mRegistrationBroadcastReceiver: "); // checking for type intent filter if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) { // gcm successfully registered // now subscribe to `global` topic to receive app wide notifications FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL); displayFirebaseRegId(); } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) { // new push notification is received String message = intent.getStringExtra("message"); Log.d(TAG,"Push notification: " + message); Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show(); // txtMessage.setText(message); } } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Fetches reg id from shared preferences // and displays on the screen private void displayFirebaseRegId() { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); String regId = pref.getString("regId", null); Log.e(TAG, "Firebase reg id: " + regId); if (!TextUtils.isEmpty(regId)) { /* RegisterEmail registerEmail = new RegisterEmail(this); SharedPreferences prefs = getSharedPreferences(Config.MY_PREFS_NAME, Context.MODE_PRIVATE); String email = prefs.getString(SettingUtil.USER_EMAIL, SettingUtil.EMPTY); registerEmail.start(URLHelp.registerEmail(email, regId));*/ // txtRegId.setText("Firebase Reg Id: " + regId); } else { // txtRegId.setText("Firebase Reg Id is not received yet!"); } } |