0

我浪费了半年的时间试图了解这项服务的问题所在。在 2.2 设备中,服务在 5 分钟后停止工作,在 4.0 设备中工作数天。
当我添加onBind()时,服务工作大约 10 个小时。
当我添加onStartCommand()返回*START_NOT_STICKY*通知不
显示在运行服务中显示的服务但不工作
任何想法我如何使它工作。

编码:

package saif.pblc.blahblah;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;

public class My_Service extends Service{
Context context = this;
//String cserver = "http://some_server/App/";
String cserver = "http://onother_server/";
final String smsverURL = cserver +"sms/smsver";
final String smsBodyURL =cserver + "sms/smsbody";
//Notification
private static final int NOTIFY_ME_ID=133333;
private NotificationManager notifyMgr=null;
//
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
    My_Service getService() {
        return My_Service.this;
    }
}
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public void onCreate() {

    notifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@SuppressLint("HandlerLeak")
@Override
public void onStart(Intent intent, int startid) {
    //Toast.makeText(this, "Service started.", Toast.LENGTH_LONG).show();
      final Handler handler = new Handler(){

         @Override
         public void handleMessage(Message msg) {
             // TODO Auto-generated method stub
             super.handleMessage(msg);
             //Toast.makeText(context, "secs has passed", Toast.LENGTH_SHORT).show();
             check_message();
         }

     };
     new Thread(new Runnable(){
         public void run() {
         // TODO Auto-generated method stub
         while(true)
         {
            try {
                handler.sendEmptyMessage(0);
                Thread.sleep(60000);


         } catch (InterruptedException e) {
             // TODO Auto-generated catch block
             //e.printStackTrace();
         } 

         }

                         }
     }).start();
}
private void check_message(){
    final SharedPreferences allData = getApplicationContext().getSharedPreferences("allData", 0);
    final float smsver =  allData.getFloat("smsVer", 0);
    final ThreadedRequest evert = new ThreadedRequest(smsverURL, "Error");
    evert.start(new Runnable() 
    {
        public void run() 
        {
            if(evert.data!="Error"||evert.data!=""){
                try{
                    final float temp = Float.parseFloat(evert.data);
                if(temp>smsver && temp>1){
                    final ThreadedRequest tReq = new ThreadedRequest(smsBodyURL, "Error");
                    tReq.start(new Runnable() 
                        {
                            public void run() 
                            {
                                if(tReq.data!="Error"){
                                    SharedPreferences.Editor editor = allData.edit();
                                    editor.putFloat("smsVer", temp);
                                    // Commit the edits!
                                    editor.commit();
                                    //Toast.makeText(context, tReq.data, Toast.LENGTH_LONG).show();
                                    String[] msg = tReq.data.split(",");
                                    My_Service.this.notify(msg[0],msg[1]);
                                }
                            }
                        });
                }
                }catch (Exception e){

                }

            }
        }
    });
}
@SuppressWarnings("deprecation")
private void notify(String title , String body){
    //Instantiate notification with icon and ticker message 

        Notification notifyObj=new Notification(R.drawable.ic_launcher, title, System.currentTimeMillis());
            //PendingIntent to launch our activity if the user selects it 
            Intent myIntent = new Intent(this, Show_Message.class);
            myIntent.putExtra("Title",title);
            myIntent.putExtra("Body",body);
            PendingIntent i=PendingIntent.getActivity(this, 0, myIntent,0);
            notifyObj.setLatestEventInfo(this, title,"Show the datails", i);
            //Value indicates the current number of events represented by the notification
            //notifyObj.number=++count;
            //Set default vibration
            notifyObj.defaults = Notification.DEFAULT_VIBRATE;
            //Set default notification sound
            notifyObj.defaults = Notification.DEFAULT_SOUND;
            //Clear the status notification when the user selects it
            notifyObj.flags =Notification.FLAG_AUTO_CANCEL;    
            //Send notification
            notifyMgr.notify(NOTIFY_ME_ID, notifyObj);
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            // Vibrate for 1000 milliseconds
            v.vibrate(1000);
}
//Class
//
public class ThreadedRequest
{
    private String url;
    private Handler mHandler;
    private Runnable pRunnable;
    private String data;
    //private int stausCode;

    public ThreadedRequest(String newUrl, String newData)
    {
        url = newUrl;
        data = newData;
        mHandler = new Handler();
    }

    public void start(Runnable newRun)
    {
        pRunnable = newRun;
        processRequest.start();
    }

    private Thread processRequest = new Thread()
    {
        public void run()
        {
            //Do you request here...
            String stringText = "";
            URL textUrl;

            try {
                textUrl = new URL(url);
                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                String StringBuffer;

                while ((StringBuffer = bufferReader.readLine()) != null) {
                    stringText += StringBuffer;
                }
                bufferReader.close();
                //stringText = Html.fromHtml(stringText).toString();
                data = stringText;
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                data = "Error";
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                data = "Error";
            }

            if (pRunnable == null || mHandler == null) return;
            mHandler.post(pRunnable);
        }
    };
}
}

谢谢

4

0 回答 0