0

i have a probleme with BroadcastReceiver & Service in my application ....... i have an * activity ( MainActivity ) * service ( NotifyService ) * Receiver ( NotifyBroadcast )

service start from activity and then the receiver start from service

everything is good when my app was open , but when i clear it (destroyed) ,receiver stop doing its job ( just a toast message )

here is my code : MainActivity ..

 if( !NotifyService.ServiceIsRun){
        NotifyService.ServiceIsRun=true;
        startService(new Intent(this, NotifyService.class));
    }

NotifyService ..

public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {       
    Timer t = new Timer();
    if(ServiceIsRun){
        t.scheduleAtFixedRate(new TimerTask() {

                                  @Override
                                  public void run() {
                                      Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
                                      i++;
                                      Intent intent = new Intent( "com.latestBabiaNews" );
                                      sendBroadcast(intent);
                                  }

                              },
                //Set how long before to start calling the TimerTask (in milliseconds)
                0,
                //Set the amount of time between each execution (in milliseconds)
                20000);
    }

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

NotifyBroadcast ..

public class NotifyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    final  Bundle bundle = intent.getExtras();
    if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){ 
       Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();

    }

}
}

And in my Manifest ..

<service android:name=".NotifyService"></service>
    <receiver android:name=".NotifyBroadcast">
        <intent-filter>
            <action android:name="com.latestBabiaNews"></action>
        </intent-filter>
    </receiver>

.......... finally i can show the Toast message when app was app was opened , but when i clear it i can't show anything !

Ouail Bellal
  • 1,554
  • 13
  • 27

1 Answers1

0

To prevent service kill use it as foreground service. To perform it as foreground use this (inside Service class):

@Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        fg();
    }
private void fg() {
        Intent intent = launchIntent(this);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
            .setContentText(getResources().getString(R.string.app_alias))
            .setContentIntent(pIntent);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(someicon);
        } else {

            mBuilder.setSmallIcon(someicon);
            mBuilder.setColor(somecolo);
        }
        noti = mBuilder.build();
        noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
        startForeground(_.ID, noti);

    }

to stop, this:

@Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        stopForeground(true);

    }

EDIT

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class MyBroadCast extends WakefulBroadcastReceiver {
    public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
    @Override
    public void onReceive(Context ctx, Intent intent) {
         Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
    }

}

To start use this:

public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
        AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
        Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
        if (autoStart)
            intent.putExtra(_.AUTOLOADSERVICE,true);

        PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
            am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
        } else {
            if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
                am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
            } else {
                    am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
            }
        }
        //or use repeating:
        //am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi); 
    }
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194