这实际上是一个拼贴项目。要求是:
我已经完成了NO:1并按预期运行,只剩下2和3。 在Background中运行此代码的最简单方法是什么:我有这样的想法:
我想使用两个按钮启动和停止后台服务。
以下是NO:1的代码。
public class SensorActivity extends Activity implements SensorEventListener{
private SensorManager mSensorManager;
private Sensor proxSensor,accSensor;
private TextView serviceStatus,profileStatus;
private Button startService,endService;
private boolean isObjectInFront,isPhoneFacedDown;
private AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
isObjectInFront = false;
isPhoneFacedDown = false;
serviceStatus = (TextView) findViewById(R.id.textView_serviceStatus);
profileStatus = (TextView) findViewById(R.id.textView_profileStatus);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if(event.values[0] > 0){
isObjectInFront = false;
}
else {
isObjectInFront = true;
}
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[2] < 0){
isPhoneFacedDown = true;
}
else {
isPhoneFacedDown = false;
}
}
if(isObjectInFront && isPhoneFacedDown){
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
profileStatus.setText("Ringer Mode : Off\nVibration Mode: Off\nSilent Mode: On");
}
else {
if(isObjectInFront){
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
profileStatus.setText("Ringer Mode : Off\nVibration Mode: On\nSilent Mode: Off");
}
else {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
profileStatus.setText("Ringer Mode : On\nVibration Mode: Off\nSilent Mode: Off");
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
答案 0 :(得分:1)
您绝对应该使用服务。
Android用户界面仅限于执行长时间运行的作业,以使用户体验更流畅。典型的长时间运行任务可以是定期从互联网下载数据,将多个记录保存到数据库中,执行文件I / O,获取手机联系人列表等。对于长时间运行的任务,服务是替代方案。
服务是用于在后台执行长时间运行任务的应用程序组件。 服务没有任何用户界面,也不能直接与活动通信。 即使启动服务的组件被销毁,服务也可以无限期地在后台运行。 通常,服务始终执行单个操作,并在预期任务完成后自行停止。 服务在应用程序实例的主线程中运行。它不会创建自己的线程。如果您的服务要进行任何长时间运行的阻塞操作,则可能导致应用程序无响应(ANR)。因此,您应该在服务中创建一个新线程。
示例强>
服务类
public class HelloService extends Service {
private static final String TAG = "HelloService";
private boolean isRunning = false;
@Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
@Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
清单声明
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javatechig.serviceexample" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".HelloActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--Service declared in manifest -->
<service android:name=".HelloService"
android:exported="false"/>
</application>
开始使用服务
Intent intent = new Intent(this, HelloService.class);
startService(intent);