如何在android中启动后台启动我的服务

时间:2015-04-01 06:28:14

标签: android performance android-intent android-activity android-service

这是我的服务类,每次都可以运行它

    public class SyncService  extends Service {

    private String loginUserInfoId = "";
    SessionManager session;
    DatabaseHelper db;
    MessageListActivity mLA;
    String otherFileName = "";
    int timer = 3000;


    long totalSize = 0;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        db = new DatabaseHelper(getApplicationContext());
        mLA = new MessageListActivity();

        session = new SessionManager(getApplicationContext());
        session.checkLogin();
        HashMap<String, String> user = session.getUserDetails();
        loginUserInfoId = user.get(SessionManager.KEY_USER_INFO_ID);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SyncMessageFromServer();
            }
        }, timer);

        final Handler handlerT = new Handler();
        handlerT.postDelayed(new Runnable() {
            @Override
            public void run() {
                SyncPendingMessageToServer();
            }
        }, 5000);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    private void SyncMessageFromServer() {
        if(Config.isInternetOn(getApplicationContext()) && loginUserInfoId != "") {
            String str = "";
            HttpResponse response;
            HttpClient myClient = new DefaultHttpClient();
            HttpPost myConnection = new HttpPost(Config.HOST_NAME+"/AndroidApp/GetAllMessage/" + loginUserInfoId);

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                JSONArray jArray = new JSONArray(str);
                for (int i = 0; i <= jArray.length() - 1; i++) {
                    JSONObject row = jArray.getJSONObject(i);
                    if (row.getString("SenderUserId") != loginUserInfoId) {
                        ChatMessage cm = new ChatMessage();

                        String currentDateTime = Config.GetCurrentDateTime();

                        String fileType = "";
                        String upFileURL = row.getString("FileAttachedURL").replace(" ", "%20");

                        if (upFileURL.contains(".jpg") || upFileURL.contains(".png")) {
                            fileType = "IMAGE";
                        }
                        else if (upFileURL.contains(".mp4")) {
                            fileType = "VIDEO";
                        }
                        else if (upFileURL.contains(".mp3")) {
                            fileType = "AUDIO";
                        }
                        else {
                            fileType = "";
                        }

                        /******* Firstly take data in model object ******/
                        cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
                        cm.setSenderUserInfoId(row.getString("SenderUserId"));
                        cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
                        cm.setMessageStatus("SENT");
                        cm.setIsPending(0);
                        cm.setIsPendingToUpdate(1);
                        cm.setMessageText(row.getString("MessageText"));
                        cm.setMediaURL("");
                        cm.setOnlineMediaURL(Config.HOST_NAME + row.getString("FileAttachedURL").replace(" ", "%20"));
                        cm.setThumbImage("");
                        cm.setIsDownloaded(0);
                        cm.setMediaMIMEType(fileType);
                        cm.setMediaSize(0);
                        cm.setMediaName("");
                        cm.setLatitude("");
                        cm.setLongitude("");
                        cm.setSendTimeStamp(currentDateTime);
                        cm.setReceiveTimeStamp("");


                        long messageId = db.SendMessage(cm);
                        //Log.d("MyService", "ChatMessageId = " + messageId);
                        Intent iMla = new Intent("REFRESH_DATA");
                        iMla.putExtra("id", messageId);
                        //intent.putExtra("id", messageId);
                        sendBroadcast(iMla);


                        String notiAvatarURL = "";
                        String notiUserName = "";
                        List<ChatMessageThread> allChatMessageThread = db.GetMessageThreadsById(row.getString("SenderUserId"));
                        for (ChatMessageThread chatMessageThread : allChatMessageThread) {

                            notiAvatarURL = chatMessageThread.getMessageThreadAvatarURL();
                            notiUserName = chatMessageThread.getMessageThreadTitle();

                        }
                        if (row.getString("SenderUserId") != loginUserInfoId) {
                            displayNotificationMessage(row.getString("MessageText"), notiAvatarURL, notiUserName);
                        }
                        confirmSyncedToServer(row.getString("MessageId"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SyncMessageFromServer();
                //SyncPendingMessageToServer();
            }
        }, timer);
    }

    private void SyncPendingMessageToServer() {
        //Toast.makeText(getApplicationContext(), "ToServer Run", Toast.LENGTH_LONG).show();
        if(Config.isInternetOn(getApplicationContext()) && loginUserInfoId != "") {
            List<ChatMessage> allChatMessage = db.getAllMessage();
            for (ChatMessage chatMessage : allChatMessage) {

                if (chatMessage.getIsPending() == 1 && chatMessage.getMediaMIMEType().isEmpty()) {
                    String msgText = chatMessage.getMessageText();

                    HttpClient myClient = new DefaultHttpClient();
                    HttpPost myConnection = new HttpPost(Config.HOST_NAME+"/AndroidApp/SendMessage");

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("messageText", msgText));
                        nameValuePairs.add(new BasicNameValuePair("senderUserInfoId", chatMessage.getSenderUserInfoId()));
                        nameValuePairs.add(new BasicNameValuePair("recieverUserInfoId", chatMessage.getReceiverUserInfoId()));
                        nameValuePairs.add(new BasicNameValuePair("url", ""));
                        nameValuePairs.add(new BasicNameValuePair("isGroupMsg", "false"));

                        myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        myClient.execute(myConnection);

                    } catch (ClientProtocolException e) {
                        Toast.makeText(getApplicationContext(), "Message sending Failed!", Toast.LENGTH_LONG).show();
                        //e.printStackTrace();
                    } catch (IOException e) {
                        //e.printStackTrace();
                    }
                }
            }
            db.updateSyncedMessage();
        }
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SyncPendingMessageToServer();
            }
        }, 10000);
    }

    public void confirmSyncedToServer(String messageId){
        HttpResponse response;
        HttpClient myClient = new DefaultHttpClient();
        HttpPost myConnection = new HttpPost(Config.HOST_NAME+"/AndroidApp/MessageSynced/" + messageId);

        try {
            response = myClient.execute(myConnection);

        } catch (ClientProtocolException e) {
            Toast.makeText(getApplicationContext(),"message sending Failed!", Toast.LENGTH_LONG).show();
            //e.printStackTrace();
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }

    private void displayNotificationMessage(String message, String notiAvatarURL, String notiUserName)
    {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        Bitmap bitmap = BitmapFactory.decodeFile(notiAvatarURL);

        mBuilder.setSmallIcon(R.drawable.psklogo);
        mBuilder.setLargeIcon(bitmap);
        mBuilder.setContentTitle(notiUserName);
        mBuilder.setContentText(message);
        mBuilder.setVibrate(new long[] { 500, 500});
        mBuilder.setLights(Color.RED, 3000, 3000);

        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(notification);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Intent resultIntent = new Intent(this, MessageThreadActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MessageThreadActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification later on.
        mNotificationManager.notify(100, mBuilder.build());
    }
}

1 个答案:

答案 0 :(得分:1)

创建一个BroadcastReceiver并注册它以接收ACTION_BOOT_COMPLETED。您还需要RECEIVE_BOOT_COMPLETED权限。

阅读:收听和广播全局消息以及设置警报

参考此answer