android 入门-Service实时向Activity通过BroadcastReceiver传递数据

引文:

http://www.cnblogs.com/linjiqin/p/3147764.html

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".EX0315" >

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/Ex0315TextView"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="0dp"
        android:text="@string/hello_world" />

    <Button android:id="@+id/Ex0315StartButton"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="40dp"
        android:text="@string/ex0315Startbutton" />
    <Button android:id="@+id/Ex0315SendButton"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="110dp"
            android:text="@string/ex0315Sendbutton" />
</RelativeLayout>
package com.iruisi.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class Ex0315Service extends Service {
    private static final String TAG = "MyService";
    private Handler mHandler=new Handler();
    private int mCount=0;
    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            mCount++;
            sendMsg2Activity("start send to service");
            Log.i("hippo","计算器"+Integer.toString(mCount));
            mHandler.postDelayed(mRunnable,1000);
        }
    };

@Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "start onCreate~~~");
        //开启服务 延时1s
        mHandler.postDelayed(mRunnable,1000);
    }

    private void sendMsg2Activity(String msg){

        //发送广播
         Intent intent=new Intent();
         intent.putExtra("count", mCount);
         intent.setAction("com.iruisi.service.Ex0315Service");
         sendBroadcast(intent);
    }
@Override
    public IBinder onBind(Intent intent) {

        return null;
    }
@Override
    public void onDestroy() {
        mHandler.removeCallbacks(mRunnable);
        super.onDestroy();
    }
@Override
    public boolean onUnbind(Intent intent) {
        // TODO Auto-generated method stub
        return super.onUnbind(intent);
    }
@Override
    public void onRebind(Intent intent) {
        // TODO Auto-generated method stub
        super.onRebind(intent);
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
}
}
package com.example.hellowrold;

import com.example.hellowrold.R.id;
import com.iruisi.service.Ex0315Service;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class EX0315 extends Activity {

    private TextView mTextView;
    private Button startButton;
    private Button sendbuButton;
    private Ex0315ServiceReceiver receiver=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ex0315);
        mTextView=(TextView)findViewById(id.Ex0315TextView);
        startButton=(Button)findViewById(id.Ex0315StartButton);
        startButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent sIntent=new Intent(EX0315.this,Ex0315Service.class);
                //sIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startService(sIntent);

                receiver=new Ex0315ServiceReceiver();
                IntentFilter mIntentFilter=new IntentFilter();
                mIntentFilter.addAction("com.iruisi.service.Ex0315Service");
                EX0315.this.registerReceiver(receiver, mIntentFilter);
            }
        });
        sendbuButton=(Button)findViewById(id.Ex0315SendButton);
        sendbuButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent sIntent=new Intent(EX0315.this,Ex0315Service.class);
                stopService(sIntent);
            }
        });
        mTextView.setText("hahh");
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.ex0315, menu);
        return true;
    }

    public class Ex0315ServiceReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle mBundle=intent.getExtras();
        int count=mBundle.getInt("count");
        mTextView=(TextView)findViewById(id.Ex0315TextView);
        mTextView.setText(String.valueOf(count));
        }
    }
}
在manifest里添加

        <service
            android:name="com.iruisi.service.Ex0315Service"
            android:exported="false" >
        </service>

 这个服务是在另外一个包里

点击发送信息到服务器按钮,其实是 "停止服务"命名错误,点击后将停止。

注意的是 在广播里重新要获取一下TextView 对象。才能显示。

时间: 2024-08-10 19:16:26

android 入门-Service实时向Activity通过BroadcastReceiver传递数据的相关文章

android 将Service绑定到Activity

Service可以和Activity绑定,后者会维持对Service实例的引用,此引用允许你像对待其他实例化的那样,对正在运行的Service进行方法调用. 允许Service和Activity绑定,这样能够获得更加详细的接口.要让一个Service支持绑定,需要实现onBind方法,并返回被绑定Service的当前实例. package com.example.androidtest.service; import android.app.Service; import android.con

Android Service实时向Activity传递数据

演示一个案例,需求如下:在Service组件中创建一个线程,该线程用来生产数值,每隔1秒数值自动加1,然后把更新后的数值在界面上实时显示. 步骤如下:1.新建一个android项目工程,取名为demo.2.新建一个Service类,用来实时生产数值,供界面实时显示. package com.ljq.activity; import android.app.Service; import android.content.Intent; import android.os.IBinder; impo

Service实时向Activity传递数据案例

转自 http://www.cnblogs.com/linjiqin/p/3147764.html 演示一个案例,需求如下:在Service组件中创建一个线程,该线程用来生产数值,每隔1秒数值自动加1,然后把更新后的数值在界面上实时显示. 步骤如下:1.新建一个android项目工程,取名为demo.2.新建一个Service类,用来实时生产数值,供界面实时显示. package com.ljq.activity;   import android.app.Service; import and

android 入门-Service

sdk 1.7 package com.example.hellowrold; import java.util.Random; import com.example.hellowrold.R.id; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.view.Menu; imp

Activity向服务传递数据

activity界面负责启动服务把数据打包,service获取数据,进行操作.具体demo如下: package com.example.android_service_trance; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.con

Activity中Intent传递数据--Bundle

<span style="font-size:18px;">///////////mainAvtivity//////////////</span> <span style="font-size:18px;">package com.demo.clf; import android.app.Activity; import android.content.Intent; import android.os.Bundle; impo

activity与fragment传递数据

activity之间的数据交换,只要Intent intent = new Intent(getContext , 将要跳转的Activity的class) ; intent.setStringExtra("tag",value) ; 在另一个activity 中 Intent intent = getIntent() ; intent.getStringExtra("tag") ; 而 activity 与 fragment 交换数据则要: activity里 B

Android使用JNI实现Java与C之间传递数据(转)

介绍Java如何将数据传递给C和C回调Java的方法.  java传递数据给C,在C代码中进行处理数据,处理完数据后返回给java.C的回调是Java传递数据给C,C需要用到Java中的某个方法,就需要调用java的方法. Android中使用JNI七个步骤: 1.创建一个android工程 2.JAVA代码中写声明native 方法 public native String helloFromJNI(); 3.用javah工具生成头文件 4. 创建jni目录,引入头文件,根据头文件实现c代码

[Android UI] Service里面启动Activity和Alertdialog

启动Activity源码:(记得要加上Intent.FLAG_ACTIVITY_NEW_TASK) Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClass(getApplicationContext(),FileBrowserActivity.class); startActivity(intent); 原因:如果一个外部的Activity Context调用sta