如何在android系统编程开始接收机功能? [英] How to begin a receiver function programmatically in android?

查看:126
本文介绍了如何在android系统编程开始接收机功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要开始通过编程接收器类,我得到了有关如何以编程启动服务,是服务的开始编程器和接收programmatically.Share您的解决方案和想法。

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.

推荐答案

如果您服务您的活动添加接收和获取数据。我想补充的活动及以下服务类。

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;
}
}

这篇关于如何在android系统编程开始接收机功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆