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
    @Override
    public IBinder onBind(Intent intent) {
        android.util.Log.d("debug", "服务在绑定的时候");
        return new MyServiceBinder();
    }

    @Override
    public 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);
            }
        }
    }

    @Override
    public 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);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        android.util.Log.d("debug", "服务在销毁的时候");
        scheduledExecutorService.shutdown();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        android.util.Log.d("debug", "服务在解绑的时候");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        android.util.Log.d("debug", "服务在重新绑定的时候");
    }

    @Override
    public 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;
        }

        @Override
        public 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 {

        @Override
        public 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;

    @Override
    public 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();
        }
    }

    @Override
    public 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;

    @Override
    protected 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);
        }
    }

    @Override
    protected 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;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        android.view.MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_upload_task_service, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public 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() {
                        @Override
                        public 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);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (uploadTaskServiceConnection != null) {
            unbindService(uploadTaskServiceConnection);
        }
    }

    @Override
    public 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);
        }
    }

    @Override
    public void onRefresh() {
        uploadTaskAdapter.setNewData(readUploadTaskEntityListForAll());
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public 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() {
                            @Override
                            public 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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值