Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Use foreground service to protect your progress being killed.
- use startService to start service
- use startForeground(NOTIFICATION_ID, notification); to prevent from desctroying.
- use your lib.
- PROFIT!
- start service:
- Intent intent = new Intent(this, HelloService.class);
- startService(intent);
- service class:
- public class ExampleService extends Service {
- @Override
- public void onCreate() {
- // The service is being created
- showForegroundNotification("some service");
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // The service is starting, due to a call to startService()
- return mStartMode;
- }
- @Override
- public IBinder onBind(Intent intent) {
- // A client is binding to the service with bindService()
- return mBinder;
- }
- @Override
- @Override
- public void onDestroy() {
- // The service is no longer used and is being destroyed
- }
- private static final int NOTIFICATION_ID = 1;
- private void showForegroundNotification(String contentText) {
- // Create intent that will bring our app to the front, as if it was tapped in the app
- // launcher
- Intent showTaskIntent = new Intent(getApplicationContext(), MyMainActivity.class);
- showTaskIntent.setAction(Intent.ACTION_MAIN);
- showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
- showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- PendingIntent contentIntent = PendingIntent.getActivity(
- getApplicationContext(),
- 0,
- showTaskIntent,
- PendingIntent.FLAG_UPDATE_CURRENT);
- Notification notification = new Notification.Builder(getApplicationContext())
- .setContentTitle(getString(R.string.app_name))
- .setContentText(contentText)
- .setSmallIcon(R.drawable.ic_notification)
- .setWhen(System.currentTimeMillis())
- .setContentIntent(contentIntent)
- .build();
- startForeground(NOTIFICATION_ID, notification);
- }
- }
- androidManifest.xml
- <service android:name=".ExampleService" . . . >
- </service>
- put pass extrad data use with:
- Intent intent = new Intent(this, HelloService.class);
- intent.putExtra("MYPARAMNAME","MYURL");
- startService(intent);
- to retrieve use this:
- onStartCommand(Intent intent, ...
- Bundle extras = intent.getExtras();
- filename = extras.getString("MYPARAMNAME");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement