当前位置: 首页 > news >正文

Android的Service和Thread的区别

Service 是一种可在后台执行长时间运行操作而不提供界面的应用组件。

Android Service是组件,既不能说它是单独的进程也不能说它是单独的线程。
如果非要从通俗的语言层面来理解的话,姑且将其理解为对象。这个Service对象本身作为应用程序的一部分与它的调用者运行在相同的进程,当然如果指定了process则会运行到另外的进程。指定到其他进程的方法参加Service属性的"android:process"。

Android Service可以在后台运行,不需要给用户提供任何的界面。但是Service是默认运行在主线程的,不要以为可以直接把它放在后台作耗时操作,如果要做耗时操作还是需要在Service里另起线程的,否则你懂得,会阻塞主线程造成ANR。
Service是组件:默认运行在当前进程的主线程中的,如果需要执行耗时操作,记得在Service里创建新线程;
Service用来提高优先级:在后台场景下,Service的优先级是高于后台挂起的Activity的,也高于Activity所创建的线程。这样的话,在内存不足时,Service不会被优先杀死


import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;import xx.MyApplication;
import xx.MySQLiteOpenHelper;
import xx.entity.UploadTaskEntity;
import xx.sharedpreference.SharedPreferenceConstant;import java.lang.ref.WeakReference;public class UploadTaskService extends android.app.Service {private MyHandler myHandler;private java.util.concurrent.ScheduledExecutorService scheduledExecutorService;private int timesForSuccess;private int timesForFailure;private int timesForNothing;@Nullable@Overridepublic IBinder onBind(Intent intent) {android.util.Log.d("debug", "服务在绑定的时候");return new MyServiceBinder();}@Overridepublic void onCreate() {super.onCreate();android.util.Log.d("debug", "服务在创建的时候");WeakReference<UploadTaskService> myServiceWeakReference = new WeakReference<UploadTaskService>(this);myHandler = new MyHandler(myServiceWeakReference);scheduledExecutorService = new java.util.concurrent.ScheduledThreadPoolExecutor(3, java.util.concurrent.Executors.defaultThreadFactory());java.util.concurrent.ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new NetworkRunnable(), 10, 30, java.util.concurrent.TimeUnit.SECONDS);boolean isDone = scheduledFuture.isDone();android.util.Log.d("debug", "调度未来是否完成->" + isDone);if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();intent.setComponent(componentName);android.content.ComponentName componentNameResult = startForegroundService(intent);if (componentNameResult != null) {android.util.Log.d("debug", "开启前台服务返回的结果->" + componentNameResult.getShortClassName());}android.app.NotificationChannel notificationChannel = new android.app.NotificationChannel("persistent", "persistent", android.app.NotificationManager.IMPORTANCE_LOW);java.lang.Object objectNotificationManger = getSystemService(NOTIFICATION_SERVICE);if (objectNotificationManger instanceof android.app.NotificationManager) {android.app.NotificationManager notificationManager = (android.app.NotificationManager) objectNotificationManger;notificationManager.createNotificationChannel(notificationChannel);android.app.Notification notification = new android.support.v4.app.NotificationCompat.Builder(this, "persistent").setAutoCancel(true).setCategory(android.app.Notification.CATEGORY_SERVICE).setOngoing(true).setPriority(android.app.NotificationManager.IMPORTANCE_LOW).build();startForeground(10, notification);}}}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {if (intent != null) {android.util.Log.d("debug", "服务在开始命令的时候(intent)->" + intent.getAction());}android.util.Log.d("debug", "服务在开始命令的时候(flags)->" + flags);android.util.Log.d("debug", "服务在开始命令的时候(startId)->" + startId);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();android.util.Log.d("debug", "服务在销毁的时候");scheduledExecutorService.shutdown();}@Overridepublic boolean onUnbind(Intent intent) {android.util.Log.d("debug", "服务在解绑的时候");return super.onUnbind(intent);}@Overridepublic void onRebind(Intent intent) {super.onRebind(intent);android.util.Log.d("debug", "服务在重新绑定的时候");}@Overridepublic void onTaskRemoved(Intent rootIntent) {super.onTaskRemoved(rootIntent);android.util.Log.d("debug", "服务在任务移除的时候");}public void startNetwork() {android.util.Log.d("debug", "手动触发上传");Thread thread = new Thread(new NetworkRunnable());thread.setName("manualThread");thread.start();}public boolean getScheduledExecutorServiceIsShutDown() {return scheduledExecutorService.isShutdown();}public java.util.Properties getProperties() {java.util.Properties properties = new java.util.Properties();properties.put("timesForSuccess", timesForSuccess);properties.put("timesForFailure", timesForFailure);properties.put("timesForNothing", timesForNothing);return properties;}private void responseSuccessForNetwork(String result) {android.util.Log.d("debug", "异步任务响应成功->" + result);timesForSuccess ++;}private void responseFailureForNetwork(String result) {android.util.Log.d("debug", "异步任务响应失败->" + result);timesForFailure ++;}private void nothingResponse() {timesForNothing ++;}public class MyServiceBinder extends android.os.Binder {public UploadTaskService getMyService() {return UploadTaskService.this;}}protected static class MyHandler extends android.os.Handler {private final WeakReference<UploadTaskService> myServiceWeakReference;public MyHandler(WeakReference<UploadTaskService> myServiceWeakReference) {this.myServiceWeakReference = myServiceWeakReference;}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);UploadTaskService uploadTaskService = myServiceWeakReference.get();if (uploadTaskService != null) {String result = (String) msg.obj;if (msg.what == -1) {uploadTaskService.nothingResponse();} else if (msg.what == 0) {uploadTaskService.responseSuccessForNetwork(result);} else if (msg.what == 1) {uploadTaskService.responseFailureForNetwork(result);}}}}protected class NetworkRunnable implements Runnable {@Overridepublic void run() {android.app.Application application = getApplication();if (application == null) {return;}android.content.SharedPreferences sharedPreferencesMulti = getSharedPreferences(SharedPreferenceConstant.NAME, android.content.Context.MODE_MULTI_PROCESS);String authorization = sharedPreferencesMulti.getString(SharedPreferenceConstant.TOKEN, null);authorization = authorization == null ? "Bearer " : "Bearer " + authorization;java.util.List<UploadTaskEntity> uploadTaskEntityList = new java.util.ArrayList<UploadTaskEntity>();MyApplication myApplication = (MyApplication) application;MySQLiteOpenHelper mySQLiteOpenHelper = myApplication.getMySQLiteOpenHelper();android.database.sqlite.SQLiteDatabase sqLiteDatabaseForReadable = mySQLiteOpenHelper.getReadableDatabase();String[] selectionArgs = new String[1];selectionArgs[0] = "0";android.database.Cursor cursor = sqLiteDatabaseForReadable.rawQuery("SELECT * FROM upload_task WHERE upload_status = ?;", selectionArgs);while (cursor.moveToNext()) {int id = cursor.getInt(cursor.getColumnIndex("id"));android.util.Log.d("debug", "id->" + id);String url = cursor.getString(cursor.getColumnIndex("url"));String method = cursor.getString(cursor.getColumnIndex("method"));String body = cursor.getString(cursor.getColumnIndex("body"));int uploadStatus = cursor.getInt(cursor.getColumnIndex("upload_status"));String remark = cursor.getString(cursor.getColumnIndex("remark"));String createTimestamp = cursor.getString(cursor.getColumnIndex("create_timestamp"));UploadTaskEntity uploadTaskEntity = new UploadTaskEntity();uploadTaskEntity.setId(id);uploadTaskEntity.setUrl(url);uploadTaskEntity.setMethod(method);uploadTaskEntity.setBody(body);uploadTaskEntity.setUploadStatus(uploadStatus);uploadTaskEntity.setRemark(remark);uploadTaskEntity.setCreateTimestamp(createTimestamp);uploadTaskEntityList.add(uploadTaskEntity);}cursor.close();if (uploadTaskEntityList.size() > 0) {for (UploadTaskEntity uploadTaskEntity : uploadTaskEntityList) {android.database.sqlite.SQLiteDatabase sqLiteDatabaseForWritable = mySQLiteOpenHelper.getWritableDatabase();android.content.ContentValues contentValues = new android.content.ContentValues(1);contentValues.put("upload_status", 1);String[] whereArgs = new String[1];whereArgs[0] = String.valueOf(uploadTaskEntity.getId());int updateResult = sqLiteDatabaseForWritable.update("upload_task", contentValues, "id = ?", whereArgs);android.util.Log.d("debug", "打印更新状态为1返回的结果->" + updateResult);boolean isSuccess = false;String result;java.net.HttpURLConnection httpURLConnection = null;java.io.BufferedReader bufferedReader = null;java.io.OutputStreamWriter outputStreamWriter = null;try {java.net.URL url = new java.net.URL(uploadTaskEntity.getUrl());android.util.Log.d("debug", "url->" + url + "\r\nrequest body->" + uploadTaskEntity.getBody());java.net.URLConnection urlConnection = url.openConnection();httpURLConnection = (java.net.HttpURLConnection) urlConnection;httpURLConnection.setRequestMethod(uploadTaskEntity.getMethod());httpURLConnection.setConnectTimeout(1000 * 30);httpURLConnection.setReadTimeout(1000 * 30);httpURLConnection.setRequestProperty("Authorization", authorization);httpURLConnection.setRequestProperty("Content-Type", "application/json");if (uploadTaskEntity.getMethod().equals("POST")) {httpURLConnection.setUseCaches(false);httpURLConnection.setDoOutput(true);}httpURLConnection.setDoInput(true);if (uploadTaskEntity.getMethod().equals("POST")) {java.io.OutputStream outputStream = httpURLConnection.getOutputStream();outputStreamWriter = new java.io.OutputStreamWriter(outputStream, "UTF-8");outputStreamWriter.write(uploadTaskEntity.getBody());outputStreamWriter.flush();} else {httpURLConnection.connect();}int responseCode = httpURLConnection.getResponseCode();if (responseCode == 200) {java.io.InputStream inputStream = httpURLConnection.getInputStream();java.io.InputStreamReader inputStreamReader = new java.io.InputStreamReader(inputStream, "UTF-8");bufferedReader = new java.io.BufferedReader(inputStreamReader);StringBuilder stringBuilder = new StringBuilder();String line;while ((line = bufferedReader.readLine()) != null) {stringBuilder.append(line);}isSuccess = true;result = stringBuilder.toString();} else {result = String.valueOf(responseCode);}android.util.Log.d("debug", "url->" + url + "\r\nresponse body->" + result);} catch (java.io.IOException ioException) {ioException.printStackTrace();result = ioException.getMessage();} finally {if (bufferedReader != null) {try {bufferedReader.close();} catch (java.io.IOException ioException) {ioException.printStackTrace();}}if (outputStreamWriter != null) {try {outputStreamWriter.close();} catch (java.io.IOException ioException) {ioException.printStackTrace();}}if (httpURLConnection != null) {httpURLConnection.disconnect();}}Message message = myHandler.obtainMessage();message.what = isSuccess ? 0 : 1;message.obj = result;boolean sentResult = myHandler.sendMessage(message);android.util.Log.d("debug", "在线程发送消息到服务返回的结果->" + sentResult);if (isSuccess) {String[] whereArgs1 = new String[1];whereArgs1[0] = String.valueOf(uploadTaskEntity.getId());int deleteResult = sqLiteDatabaseForWritable.delete("upload_task", "id = ?", whereArgs1);android.util.Log.d("debug", "打印上传成功之后删除本地的返回的结果->" + deleteResult);} else {android.content.ContentValues contentValues1 = new android.content.ContentValues(2);contentValues1.put("upload_status", 0);contentValues1.put("remark", result);String[] whereArgs1 = new String[1];whereArgs1[0] = String.valueOf(uploadTaskEntity.getId());int updateResult1 = sqLiteDatabaseForWritable.update("upload_task", contentValues1, "id = ?", whereArgs1);android.util.Log.d("debug", "打印更新上传状态为0返回的结果->" + updateResult1);}}} else {android.util.Log.d("debug", "暂无可上传的任务");boolean sentResult = myHandler.sendEmptyMessage(-1);android.util.Log.d("debug", "发送空消息返回的结果->" + sentResult);}}}
}

ServiceConnection是Service和Activity通讯的组件

import android.content.ComponentName;
import android.os.IBinder;public class UploadTaskServiceConnection implements android.content.ServiceConnection {private UploadTaskService uploadTaskService = null;@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {android.util.Log.d("debug", "在服务连接的时候(name)->" + name.getShortClassName());if (service instanceof UploadTaskService.MyServiceBinder) {UploadTaskService.MyServiceBinder myServiceBinder = (UploadTaskService.MyServiceBinder) service;uploadTaskService = myServiceBinder.getMyService();}}@Overridepublic void onServiceDisconnected(ComponentName name) {android.util.Log.d("debug", "在服务断开连接的时候(name)->" + name.getShortClassName());}public UploadTaskService getMyService() {return uploadTaskService;}
}

Activity和Service之间通讯的示例

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;import xx.R;
import xx.adapter.UploadTaskAdapter;
import xx.pub.MyApplication;
import xx.pub.db.MySQLiteOpenHelper;
import xx.pub.entity.UploadTaskEntity;
import xx.service.UploadTaskService;
import xx.service.UploadTaskServiceConnection;public class UploadTaskServiceActivity extends android.support.v7.app.AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, UploadTaskAdapter.OnItemChildClickListenerForCustom {private UploadTaskServiceConnection uploadTaskServiceConnection = null;private UploadTaskAdapter uploadTaskAdapter;private android.support.v4.widget.SwipeRefreshLayout swipeRefreshLayout;private android.widget.TextView textViewDisplayProperties;private android.widget.TextView textViewServiceIsRunning;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_upload_task_service);android.support.v7.widget.Toolbar toolbar = findViewById(R.id.activity_upload_task_service_toolbar);setSupportActionBar(toolbar);android.widget.Button buttonStartService = findViewById(R.id.activity_upload_task_service_button_start_service);android.widget.Button buttonStopService = findViewById(R.id.activity_upload_task_service_button_stop_service);android.widget.Button buttonBindService = findViewById(R.id.activity_upload_task_service_button_bind_service);android.widget.Button buttonUnbindService = findViewById(R.id.activity_upload_task_service_button_unbind_service);android.widget.Button buttonNetworkOnService = findViewById(R.id.activity_upload_task_service_button_network_on_service);android.widget.Button buttonGetScheduledStatus = findViewById(R.id.activity_upload_task_service_button_get_scheduled_status);android.widget.Button buttonGetProperties = findViewById(R.id.activity_upload_task_service_button_get_properties);android.widget.Button buttonGetServiceIsRunning = findViewById(R.id.activity_upload_task_service_button_get_service_is_running);textViewDisplayProperties = findViewById(R.id.activity_upload_task_service_text_display_properties);textViewServiceIsRunning = findViewById(R.id.activity_upload_task_service_text_view_service_is_running);buttonStartService.setOnClickListener(this);buttonStopService.setOnClickListener(this);buttonBindService.setOnClickListener(this);buttonUnbindService.setOnClickListener(this);buttonNetworkOnService.setOnClickListener(this);buttonGetScheduledStatus.setOnClickListener(this);buttonGetProperties.setOnClickListener(this);buttonGetServiceIsRunning.setOnClickListener(this);swipeRefreshLayout = findViewById(R.id.activity_upload_task_service_swipe_refresh_layout);swipeRefreshLayout.setOnRefreshListener(this);android.widget.ListView listView = findViewById(R.id.activity_upload_task_service_list_view);uploadTaskAdapter = new UploadTaskAdapter(this, readUploadTaskEntityListForAll());uploadTaskAdapter.setOnItemChildClickListenerForCustom(this);listView.setAdapter(uploadTaskAdapter);}private boolean isRunningForService() {boolean isRunning = false;Object activityServiceObject = getSystemService(ACTIVITY_SERVICE);if (activityServiceObject instanceof android.app.ActivityManager) {android.content.ComponentName componentNameOfMyService = new android.content.ComponentName(this, UploadTaskService.class);android.app.ActivityManager activityManager = (android.app.ActivityManager) activityServiceObject;java.util.List<android.app.ActivityManager.RunningServiceInfo> runningServiceInfoList = activityManager.getRunningServices(Integer.MAX_VALUE);if (runningServiceInfoList != null && runningServiceInfoList.size() > 0) {for (android.app.ActivityManager.RunningServiceInfo runningServiceInfo : runningServiceInfoList) {android.content.ComponentName componentName = runningServiceInfo.service;String className = componentName.getClassName();android.util.Log.d("debug", "正在运行中的服务->" + className);int compareResult = componentName.compareTo(componentNameOfMyService);android.util.Log.d("debug", "打印比较结果->" + compareResult);if (compareResult == 0) {isRunning = true;break;}}}}return isRunning;}private void bindService() {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();android.content.Intent intentResult = intent.setComponent(componentName);uploadTaskServiceConnection = new UploadTaskServiceConnection();boolean bindServiceResult = bindService(intent, uploadTaskServiceConnection, 0);String text = "绑定服务的结果:" + bindServiceResult;android.util.Log.d("debug", text);}private void startService() {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();android.content.Intent intentResult = intent.setComponent(componentName);android.content.ComponentName componentNameResult = startService(intent);if (componentNameResult != null) {String shortClassName = componentNameResult.getShortClassName();android.util.Log.d("debug", "开始的服务的短类名->" + shortClassName);}}@Overrideprotected void onResume() {super.onResume();if (isRunningForService()) {if (uploadTaskServiceConnection != null) {unbindService(uploadTaskServiceConnection);uploadTaskServiceConnection = null;}} else {startService();}bindService();}private java.util.List<UploadTaskEntity> readUploadTaskEntityListForAll() {MyApplication myApplication = (MyApplication) getApplication();MySQLiteOpenHelper mySQLiteOpenHelper = myApplication.getMySQLiteOpenHelper();android.database.sqlite.SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getReadableDatabase();android.database.Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM upload_task;", null);java.util.List<UploadTaskEntity> uploadTaskEntityList = new java.util.ArrayList<UploadTaskEntity>();while (cursor.moveToNext()) {int id = cursor.getInt(cursor.getColumnIndex("id"));String url = cursor.getString(cursor.getColumnIndex("url"));String method = cursor.getString(cursor.getColumnIndex("method"));String body = cursor.getString(cursor.getColumnIndex("body"));int uploadStatus = cursor.getInt(cursor.getColumnIndex("upload_status"));String remark = cursor.getString(cursor.getColumnIndex("remark"));String createTimestamp = cursor.getString(cursor.getColumnIndex("create_timestamp"));UploadTaskEntity uploadTaskEntity = new UploadTaskEntity();uploadTaskEntity.setId(id);uploadTaskEntity.setUrl(url);uploadTaskEntity.setMethod(method);uploadTaskEntity.setBody(body);uploadTaskEntity.setUploadStatus(uploadStatus);uploadTaskEntity.setRemark(remark);uploadTaskEntity.setCreateTimestamp(createTimestamp);uploadTaskEntityList.add(uploadTaskEntity);}cursor.close();return uploadTaskEntityList;}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {android.view.MenuInflater menuInflater = getMenuInflater();menuInflater.inflate(R.menu.menu_upload_task_service, menu);return super.onCreateOptionsMenu(menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {if (item.getItemId() == android.R.id.home) {finish();} else if (item.getItemId() == R.id.menu_test_service_create_upload_task) {View view = android.view.LayoutInflater.from(this).inflate(R.layout.dialog_create_upload_task, null);final android.widget.EditText editTextUrl = view.findViewById(R.id.dialog_create_upload_task_edit_text_url);final android.widget.EditText editTextMethod = view.findViewById(R.id.dialog_create_upload_task_edit_text_method);final android.widget.EditText editTextBody = view.findViewById(R.id.dialog_create_upload_task_edit_text_body);new AlertDialog.Builder(this).setView(view).setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {String url = editTextUrl.getText().toString();String method = editTextMethod.getText().toString();String body = editTextBody.getText().toString();android.app.Application application = getApplication();MyApplication myApplication = (MyApplication) application;MySQLiteOpenHelper mySQLiteOpenHelper = myApplication.getMySQLiteOpenHelper();android.database.sqlite.SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();android.content.ContentValues contentValues = new android.content.ContentValues(4);contentValues.put("url", url);contentValues.put("method", method);contentValues.put("body", body);contentValues.put("upload_status", 0);long insertResult = sqLiteDatabase.insert("upload_task", null, contentValues);android.util.Log.d("debug", "插入结果->" + insertResult);Toast.makeText(UploadTaskServiceActivity.this, "创建上传任务结果:" + insertResult, Toast.LENGTH_SHORT).show();uploadTaskAdapter.setNewData(readUploadTaskEntityListForAll());}}).create().show();}return super.onOptionsItemSelected(item);}@Overrideprotected void onDestroy() {super.onDestroy();if (uploadTaskServiceConnection != null) {unbindService(uploadTaskServiceConnection);}}@Overridepublic void onClick(View v) {if (v.getId() == R.id.activity_upload_task_service_button_start_service) {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();android.content.Intent intentResult = intent.setComponent(componentName);android.content.ComponentName componentNameResult = startService(intent);if (componentNameResult != null) {String shortClassName = componentNameResult.getShortClassName();android.util.Log.d("debug", "开始的服务的短类名->" + shortClassName);String className = componentNameResult.getClassName();android.util.Log.d("debug", "开始的服务的类名->" + className);String text = "开始服务的类名:" + shortClassName;Toast.makeText(this, text, Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_stop_service) {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();android.content.Intent intentResult = intent.setComponent(componentName);boolean stopServiceResult = stopService(intent);String text = "停止服务的结果:" + stopServiceResult;Toast.makeText(this, text, Toast.LENGTH_SHORT).show();} else if (v.getId() == R.id.activity_upload_task_service_button_bind_service) {if (uploadTaskServiceConnection != null) {Toast.makeText(this, "服务已经绑定,无需重复绑定", Toast.LENGTH_SHORT).show();} else {android.content.ComponentName componentName = new android.content.ComponentName(this, UploadTaskService.class);android.content.Intent intent = new android.content.Intent();android.content.Intent intentResult = intent.setComponent(componentName);uploadTaskServiceConnection = new UploadTaskServiceConnection();boolean bindServiceResult = bindService(intent, uploadTaskServiceConnection, 0);String text = "绑定服务的结果:" + bindServiceResult;Toast.makeText(this, text, Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_unbind_service) {if (uploadTaskServiceConnection != null) {unbindService(uploadTaskServiceConnection);uploadTaskServiceConnection = null;Toast.makeText(this, "解除绑定完成", Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "无绑定服务,不用解绑", Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_network_on_service) {if (uploadTaskServiceConnection != null) {UploadTaskService uploadTaskService = uploadTaskServiceConnection.getMyService();if (uploadTaskService != null) {uploadTaskService.startNetwork();Toast.makeText(this, "后台服务已经在上传...", Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "服务是空的,可能是绑定失败", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(this, "还没有绑定服务,请先绑定服务", Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_get_scheduled_status) {if (uploadTaskServiceConnection != null) {UploadTaskService uploadTaskService = uploadTaskServiceConnection.getMyService();if (uploadTaskService != null) {boolean isShutDown = uploadTaskService.getScheduledExecutorServiceIsShutDown();Toast.makeText(this, "调度服务是否关闭:" + isShutDown, Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "服务是空的,可能是绑定失败", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(this, "还没有绑定服务,请先绑定服务", Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_get_properties) {if (uploadTaskServiceConnection != null) {UploadTaskService uploadTaskService = uploadTaskServiceConnection.getMyService();if (uploadTaskService != null) {java.util.Properties properties = uploadTaskService.getProperties();Integer timesForSuccess = (Integer) properties.get("timesForSuccess");Integer timesForFailure = (Integer) properties.get("timesForFailure");Integer timesForNothing = (Integer) properties.get("timesForNothing");String text = "success:" + timesForSuccess + ";failure:" + timesForFailure + ";nothing:" + timesForNothing;textViewDisplayProperties.setText(text);} else {Toast.makeText(this, "服务是空的,可能是绑定失败", Toast.LENGTH_SHORT).show();}} else {Toast.makeText(this, "还没有绑定服务,请先绑定服务", Toast.LENGTH_SHORT).show();}} else if (v.getId() == R.id.activity_upload_task_service_button_get_service_is_running) {boolean isRunning = false;Object activityServiceObject = getSystemService(ACTIVITY_SERVICE);if (activityServiceObject instanceof android.app.ActivityManager) {android.content.ComponentName componentNameOfMyService = new android.content.ComponentName(this, UploadTaskService.class);android.app.ActivityManager activityManager = (android.app.ActivityManager) activityServiceObject;java.util.List<android.app.ActivityManager.RunningServiceInfo> runningServiceInfoList = activityManager.getRunningServices(Integer.MAX_VALUE);if (runningServiceInfoList != null && runningServiceInfoList.size() > 0) {for (android.app.ActivityManager.RunningServiceInfo runningServiceInfo : runningServiceInfoList) {android.content.ComponentName componentName = runningServiceInfo.service;String className = componentName.getClassName();android.util.Log.d("debug", "正在运行中的服务->" + className);int compareResult = componentName.compareTo(componentNameOfMyService);android.util.Log.d("debug", "打印比较结果->" + compareResult);if (compareResult == 0) {isRunning = true;break;}}}}String text = "后台上传服务是否在运行:" + isRunning;textViewServiceIsRunning.setText(text);}}@Overridepublic void onRefresh() {uploadTaskAdapter.setNewData(readUploadTaskEntityListForAll());swipeRefreshLayout.setRefreshing(false);}@Overridepublic void onItemChildClickForCustom(Integer position, int viewId) {Object object = uploadTaskAdapter.getItem(position);if (object instanceof UploadTaskEntity) {final UploadTaskEntity uploadTaskEntity = (UploadTaskEntity) object;if (viewId == R.id.item_upload_task_text_view_delete) {String message = "你确定要删除任务ID为" + uploadTaskEntity.getId() + "的上传任务吗?";new AlertDialog.Builder(this).setMessage(message).setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {int deleteResult = deleteUploadTaskEntityById(uploadTaskEntity.getId());Toast.makeText(UploadTaskServiceActivity.this, "删除数量:" + deleteResult, Toast.LENGTH_SHORT).show();uploadTaskAdapter.setNewData(readUploadTaskEntityListForAll());}}).create().show();} else if (viewId == R.id.item_upload_task_text_view_copy) {Object objectForClipboardService = getSystemService(CLIPBOARD_SERVICE);if (objectForClipboardService instanceof android.content.ClipboardManager) {android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) objectForClipboardService;clipboardManager.setText(uploadTaskEntity.toString());Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();}}}}private int deleteUploadTaskEntityById(int id) {MyApplication myApplication = (MyApplication) getApplication();MySQLiteOpenHelper mySQLiteOpenHelper = myApplication.getMySQLiteOpenHelper();android.database.sqlite.SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();String[] whereArgs = new String[1];whereArgs[0] = String.valueOf(id);return sqLiteDatabase.delete("upload_task", "id = ?", whereArgs);}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 将pytorch配置到jupyter里面(个人踩坑向)
  • HarmonyOS开发案例:创建全局自定义组件复用池-BuilderNode
  • 网鼎杯-2018-Web-Unfinish
  • python从入门到精通:函数
  • 安企CMS多站点迁移教程
  • 秋招突击——面经整理——有塔游戏提前批
  • AtCoder Beginner Contest 366 A~F
  • Mysql 约束(下)
  • 掌握这项技能,用Python爬虫定制你的私人电影推荐库
  • 【计算机网络】计算机网络第二章——信道复用技术
  • Ubuntu 22.04 安装 VirtualBox7
  • 怎么给图片加红色边框?图片加边框的超好用方法
  • 设计模式六大原则之:依赖倒置原则
  • [二次元]个人主页搭建
  • 虚拟化—XenServer安装教程详细(附客户端连接)
  • 2018一半小结一波
  • chrome扩展demo1-小时钟
  • Computed property XXX was assigned to but it has no setter
  • Intervention/image 图片处理扩展包的安装和使用
  • JAVA_NIO系列——Channel和Buffer详解
  • SpingCloudBus整合RabbitMQ
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • Vue2.x学习三:事件处理生命周期钩子
  • 基于 Babel 的 npm 包最小化设置
  • 基于webpack 的 vue 多页架构
  • 罗辑思维在全链路压测方面的实践和工作笔记
  • 什么软件可以提取视频中的音频制作成手机铃声
  • 小而合理的前端理论:rscss和rsjs
  • 原创:新手布局福音!微信小程序使用flex的一些基础样式属性(一)
  • 阿里云重庆大学大数据训练营落地分享
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • (007)XHTML文档之标题——h1~h6
  • (13):Silverlight 2 数据与通信之WebRequest
  • (层次遍历)104. 二叉树的最大深度
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (附源码)ssm经济信息门户网站 毕业设计 141634
  • (四) Graphivz 颜色选择
  • (一)utf8mb4_general_ci 和 utf8mb4_unicode_ci 适用排序和比较规则场景
  • (原)本想说脏话,奈何已放下
  • (转)Google的Objective-C编码规范
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler
  • .net core使用RPC方式进行高效的HTTP服务访问
  • .Net MVC + EF搭建学生管理系统
  • .net php 通信,flash与asp/php/asp.net通信的方法
  • .NET 除了用 Task 之外,如何自己写一个可以 await 的对象?
  • .net2005怎么读string形的xml,不是xml文件。
  • .Net开发笔记(二十)创建一个需要授权的第三方组件
  • .NET中使用Protobuffer 实现序列化和反序列化
  • /etc/X11/xorg.conf 文件被误改后进不了图形化界面
  • [ C++ ] STL---string类的使用指南
  • [ vulhub漏洞复现篇 ] Apache APISIX 默认密钥漏洞 CVE-2020-13945
  • [AIGC] 广度优先搜索(Breadth-First Search,BFS)详解
  • [BUUCTF]-PWN:wustctf2020_number_game解析(补码,整数漏洞)
  • [C++]使用yolov10的onnx模型结合onnxruntime和bytetrack实现目标追踪