Android从服务中获取信息

时间:2016-01-15 07:07:52

标签: android android-service

我做了一个每10秒触发一次的服务。如何在触发时将服务连接到活动。示例i刷新我的本地数据库,当出现更新活动发送Toast时。

AlarmService.class

    @SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {

    Handler mHandler;
    private PendingIntent pendingIntent;

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

    @Override
    public void onCreate() {
    }

    public void f() {
        Toast t = Toast.makeText(this, "Service is still running",
                Toast.LENGTH_SHORT);
        t.show();
    }

    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
        t.show();

        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        mHandler = new Handler();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                f();
                mHandler.postDelayed(this,10000);
            }
        };
        mHandler.postDelayed(r, 10000);
    }
}

MainActivity.class

public class MainActivity extends AppCompatActivity {

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

       Intent serviceIntent = new Intent(this,AlarmService.class);
        startService(serviceIntent);

    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用LocalBroadcastManagerMessengerResultReceiver将数据从服务发送到Activity

Here是一个使用ResultReceiver将更新数据从Service发送到Activity的示例。

答案 1 :(得分:0)

像这样使用广播接收器

public static class MyExtBroadcastReceiver extends BroadcastReceiver {

    public MyExtBroadcastReceiver() { 
         super();
    } 

    @Override
    public void onReceive(Context context, Intent intent) {
     //Call your activity here      
    }

制作一种设置闹钟的方法

 public void setAlarm(){
    f(); // call your method f() here 
    AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
    Intent alarmintent1 = new Intent(this, MyExtBroadcastReceiver.class);
    PendingIntent sender1=PendingIntent.getBroadcast(this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
    try {
        am.cancel(sender1);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("ex....."+e);
    }

    Calendar cal=Calendar.getInstance();
    cal.add(Calendar.Seconds,10);
    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10*60, sender1);

从OnCreate()

调用此方法
@Override
public void onCreate() {
  setAlarm();

}
}