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");
     //其实不用在广播里重新要获取一下TextView 对象 setText参数是字符串类型,不是整型 //mTextView
=(TextView)findViewById(id.Ex0315TextView); mTextView.setText(String.valueOf(count)); } } }
在manifest里添加

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

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

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

原文地址:https://www.cnblogs.com/androllen/p/4160327.html