Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. Use foreground service to protect your progress being killed.
  2.  
  3. use startService to start service
  4.  
  5. use startForeground(NOTIFICATION_ID, notification); to prevent from desctroying.
  6.  
  7. use your lib.
  8.  
  9. PROFIT!
  10.  
  11. start service:
  12.  
  13. Intent intent = new Intent(this, HelloService.class);
  14. startService(intent);
  15.  
  16. service class:
  17. public class ExampleService extends Service {
  18.  
  19. @Override
  20. public void onCreate() {
  21. // The service is being created
  22. showForegroundNotification("some service");
  23. }
  24. @Override
  25. public int onStartCommand(Intent intent, int flags, int startId) {
  26. // The service is starting, due to a call to startService()
  27. return mStartMode;
  28. }
  29. @Override
  30. public IBinder onBind(Intent intent) {
  31. // A client is binding to the service with bindService()
  32. return mBinder;
  33. }
  34. @Override
  35.  
  36. @Override
  37. public void onDestroy() {
  38. // The service is no longer used and is being destroyed
  39. }
  40. private static final int NOTIFICATION_ID = 1;
  41.  
  42. private void showForegroundNotification(String contentText) {
  43. // Create intent that will bring our app to the front, as if it was tapped in the app
  44. // launcher
  45. Intent showTaskIntent = new Intent(getApplicationContext(), MyMainActivity.class);
  46. showTaskIntent.setAction(Intent.ACTION_MAIN);
  47. showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
  48. showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  49.  
  50. PendingIntent contentIntent = PendingIntent.getActivity(
  51. getApplicationContext(),
  52. 0,
  53. showTaskIntent,
  54. PendingIntent.FLAG_UPDATE_CURRENT);
  55.  
  56. Notification notification = new Notification.Builder(getApplicationContext())
  57. .setContentTitle(getString(R.string.app_name))
  58. .setContentText(contentText)
  59. .setSmallIcon(R.drawable.ic_notification)
  60. .setWhen(System.currentTimeMillis())
  61. .setContentIntent(contentIntent)
  62. .build();
  63. startForeground(NOTIFICATION_ID, notification);
  64. }
  65. }
  66.  
  67. androidManifest.xml
  68.  
  69. <service android:name=".ExampleService" . . . >
  70. </service>
  71. put pass extrad data use with:
  72.  
  73. Intent intent = new Intent(this, HelloService.class);
  74. intent.putExtra("MYPARAMNAME","MYURL");
  75. startService(intent);
  76.  
  77. to retrieve use this:
  78.  
  79. onStartCommand(Intent intent, ...
  80. Bundle extras = intent.getExtras();
  81. filename = extras.getString("MYPARAMNAME");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement