第十二章:访问Android服务
一. 创建自己的服务
服务是Android中的一个应用,他在后台运行,不需要与用户有任何交互。如 当使用一个应用时,你希望同时可以在后台播放音乐。这时,在后台播放音乐的代码不需要与用户交互;因此他可以作为一个服务运行。同时,应用不需要提供UI时,服务也是理想的选择
MyService类中实现三个方法:
onBind()使你能将一个Activity绑定到一个服务上
onStartCommand()该方***在显示的使用startService()方法启动服务时被调用。该方法表示服务启动,可以在该方法中编写任何想要为服务执行 的任务
onDestroy() 该方***在显示的使用stopService()方法停止服务时被调用,在该方法中清理服务使用的资源。
二. 在服务和Activity之间建立通信
三. 将Activity与服务绑定
四. 线程的概念
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jfdimarzio.services.MainActivity">
<Button
android:text="Start Service"
android:layout_width="90dp"
android:layout_height="50dp"
android:id="@+id/btnStartService"
app:layout_constraintLeft_toLeftOf="@+id/activity_main"
app:layout_constraintTop_toTopOf="@+id/activity_main"
android:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="@+id/activity_main"
app:layout_constraintBottom_toTopOf="@+id/btnStopService"
android:layout_marginBottom="8dp"
android:onClick="startService" />
<Button
android:text="Stop Service"
android:layout_width="88dp"
android:layout_height="48dp"
android:id="@+id/btnStopService"
android:onClick="stopService"
app:layout_constraintLeft_toLeftOf="@+id/activity_main"
android:layout_marginStart="16dp"
app:layout_constraintTop_toTopOf="@+id/activity_main"
app:layout_constraintRight_toRightOf="@+id/activity_main"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="@+id/activity_main" />
</android.support.constraint.ConstraintLayout>
package com.jfdimarzio.services;
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter;
MyService serviceBinder;
Intent i;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(
ComponentName className, IBinder service) {
//—-called when the connection is made—-
serviceBinder = ((MyService.MyBinder)service).getService();
try {
URL[] urls = new URL[] {
new URL("http://www.amazon.com/somefiles.pdf"),
new URL("http://www.wrox.com/somefiles.pdf"),
new URL("http://www.google.com/somefiles.pdf"),
new URL("http://www.learn2develop.net/somefiles.pdf")};
//---assign the URLs to the service through the
// serviceBinder object---
serviceBinder.urls = urls;
} catch (MalformedURLException e) {
e.printStackTrace();
}
startService(i);
}
public void onServiceDisconnected(ComponentName className) {
//---called when the service disconnects---
serviceBinder = null;
}
};
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onResume() {
super.onResume();
//---intent to filter for file downloaded intent---
intentFilter = new IntentFilter();
intentFilter.addAction("FILE_DOWNLOADED_ACTION");
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
}
public void onPause() {
super.onPause();
//---unregister the receiver---
unregisterReceiver(intentReceiver);
}
public void startService(View view) {
i = new Intent(MainActivity.this, MyService.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
}
public void stopService(View view) {
stopService(new Intent(MainActivity.this, MyIntentService.class));
}
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Toast.makeText(getBaseContext(), "File downloaded!",
Toast.LENGTH_LONG).show();
}
};
}
package com.jfdimarzio.services;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.net.MalformedURLException;
import java.net.URL;
public class MyIntentService extends IntentService {
private Thread thread = new Thread();
public MyIntentService() {
super("MyIntentServiceName");
}
protected void onHandleIntent(Intent intent) {
try {
int result =
DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
thread.start();
Log.d("IntentService", "Downloaded " + result + " bytes");
//---send a broadcast to inform the activity
// that the file has been downloaded---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
getBaseContext().sendBroadcast(broadcastIntent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private int DownloadFile(URL url) {
try {
//---simulate taking some time to download a file---
thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 100;
}
public void onDestroy() {
thread.interrupt();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
package com.jfdimarzio.services;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
int counter = 0;
URL[] urls;
static final int UPDATE_INTERVAL = 1000;
private Timer timer = new Timer();
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
public IBinder onBind(Intent arg0) {
return binder;
}
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
new DoBackgroundTask().execute(urls);
return START_STICKY;
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.d("MyService", String.valueOf(++counter));
}
}, 0, UPDATE_INTERVAL);
}
private int DownloadFile(URL url) {
try {
//---simulate taking some time to download a file---
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//---return an arbitrary number representing
// the size of the file downloaded---
return 100;
}
private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalBytesDownloaded = 0;
for (int i = 0; i < count; i++) {
totalBytesDownloaded += DownloadFile(urls[i]);
//---calculate percentage downloaded and
// report its progress---
publishProgress((int) (((i+1) / (float) count) * 100));
}
return totalBytesDownloaded;
}
protected void onProgressUpdate(Integer... progress) {
Log.d("Downloading files",
String.valueOf(progress[0]) + "% downloaded");
Toast.makeText(getBaseContext(),
String.valueOf(progress[0]) + "% downloaded",
Toast.LENGTH_LONG).show();
}
protected void onPostExecute(Long result) {
Toast.makeText(getBaseContext(),
"Downloaded " + result + " bytes",
Toast.LENGTH_LONG).show();
stopSelf();
}
}
public void onDestroy() {
super.onDestroy();
if (timer != null){
timer.cancel();
}
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}


查看1道真题和解析