3分钟
4.3 实施步骤
实施步骤
步骤1:新建项目,命名为myBroadcast。
步骤2:新建一个接口文件ICounterService.java,如表4-3-1所示
表4-3-1 ICounterService.java 文件清单
package com.example.mybroadcast;
public interface ICounterService {
public void startCounter(int initVal);
public void stopCounter();
}步骤3:新建一个Service文件CounterService.java ,用于实现后台计数,如表4-3-2所示。
表4-3-2 CounterService.java文件清单
package com.example.mybroadcast;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class CounterService extends Service implements ICounterService {
private final static String LOG_TAG = "chen";
public final static String BROADCAST_COUNTER_ACTION =
"com.example.mybroadcast.COUNTER_ACTION";
public final static String COUNTER_VALUE =
"com.example.mybroadcast.counter.value";
private boolean stop = false;
private final IBinder binder = new CounterBinder();
public class CounterBinder extends Binder {
public CounterService getService() {
return CounterService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "Counter Service Created.");
}
@Override
public void onDestroy() {
Log.i(LOG_TAG, "Counter Service Destroyed.");
super.onDestroy();
}
public void startCounter(int initVal) {
AsyncTask<Integer, Integer, Integer> task = new AsyncTask<Integer, Integer, Integer>() {
@Override
protected Integer doInBackground(Integer... vals) {
Integer initCounter = vals[0];
stop = false;
while(!stop) {
publishProgress(initCounter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
initCounter++;
}
return initCounter;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int counter = values[0];
Intent intent = new Intent(BROADCAST_COUNTER_ACTION);
intent.putExtra(COUNTER_VALUE, counter);
sendBroadcast(intent);
}
@Override
protected void onPostExecute(Integer val) {
int counter = val;
Intent intent = new Intent(BROADCAST_COUNTER_ACTION);
intent.putExtra(COUNTER_VALUE, counter);
sendBroadcast(intent);
}
};
task.execute(0);
}
public void stopCounter() {
stop = true;
Log.e(LOG_TAG, "stopCounter: ");
}
}步骤3:修改主文件MainActivity.java ,如表4-3-3所示。
表4-3-3 MainActivity.java文件清单
package com.example.mybroadcast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements OnClickListener{
private final static String LOG_TAG = "chen";
private Button startButton = null;
private Button stopButton = null;
private TextView counterText = null;
private ICounterService counterService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button)findViewById(R.id.button_start);
stopButton = (Button)findViewById(R.id.button_stop);
counterText = (TextView)findViewById(R.id.textview_counter);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
startButton.setEnabled(true);
stopButton.setEnabled(false);
Intent bindIntent = new Intent(MainActivity.this, CounterService.class);
bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
Log.e(LOG_TAG, "Main Activity Created.");
}
@Override
public void onResume() {
super.onResume();
IntentFilter counterActionFilter = new IntentFilter(CounterService.BROADCAST_COUNTER_ACTION);
registerReceiver(counterActionReceiver, counterActionFilter);
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(counterActionReceiver);
}
@Override
public void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
@Override
public void onClick(View v) {
if(v.equals(startButton)) {
if(counterService != null) {
counterService.startCounter(0);
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
} else if(v.equals(stopButton)) {
if(counterService != null) {
counterService.stopCounter();
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
}
}
private BroadcastReceiver counterActionReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
int counter = intent.getIntExtra(CounterService.COUNTER_VALUE, 0);
String text = String.valueOf(counter);
counterText.setText(text);
Log.i(LOG_TAG, "Receive counter event");
}
};
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
counterService = ((CounterService.CounterBinder)service).getService();
Log.i(LOG_TAG, "Counter Service Connected");
}
public void onServiceDisconnected(ComponentName className) {
counterService = null;
Log.i(LOG_TAG, "Counter Service Disconnected");
}
};
}步骤4:修改布局文件activity_main.xml,如表4-3-4所示。
表4-3-4 activity_main.xml文件清单
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10px"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4px"
android:gravity="center"
android:text="@string/counter">
</TextView>
<TextView
android:id="@+id/textview_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/start">
</Button>
<Button
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/stop" >
</Button>
</LinearLayout>
</LinearLayout>步骤5:新建变量文件string.xml,如表4-3-5所示。
表4-3-5 string.xml文件清单
<resources>
<string name="app_name">myBroadcast</string>
<string name="counter">Counter: </string>
<string name="start">Start Counter</string>
<string name="stop">Stop Counter</string>
</resources>步骤6:注册Service,修改文件AndroidManifest.xml ,如表4-3-6所示。
表4-3-6 AndroidManifest.xml文件清单
<service android:name=".CounterService"
android:enabled="true">
</service>步骤7:在手机上运行并观察效果。
学员评价