How to begin a receiver function programmatically

2019-09-16 18:21发布

问题:

I want to begin the receiver class by programmatically,I got some idea about how to start service programmatically and what is the difference between beginning service programmatically and receiver programmatically.Share your solutions and ideas.

回答1:

If you add receiver in service and get data from your activity. I add Activity and Service class below.

This is your main activity when you get receive data from service.

public class YourActivity extends Activity {
private MyReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
    receiver = new MyReceiver();
    IntentFilter filter = new IntentFilter(YourServices.ACTION);
    manager.registerReceiver(receiver, filter);

    if (!YourServices.isRunning) {
        startService(new Intent(this, YourServices.class));
    }
}

class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null) {
    if (intent.getAction().equals(YourServices.ACTION)) {
    AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, MyServiceReceiver.class);
    PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    // Start 20 seconds after boot completed
    cal.add(Calendar.SECOND, 20);
    Log.v("background service", "STARTED////\\");

    //
    // Fetch every 1 hour
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pending);
            }
        }
    }
}
}

Here your service that send data when starting.

public class YourServices extends Service {

public static String ACTION = "your_action";
public static boolean isRunning = true;

private void broadcastData() {
    Intent intent = new Intent(ACTION);
    LocalBroadcastManager.getInstance(getApplicationContext())
            .sendBroadcast(intent);
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    broadcastData();
    return START_STICKY;
}
}