保持服务定期唤醒android

时间:2015-07-05 08:18:04

标签: android service android-wake-lock

我有一个基于服务的应用程序。我的目标是即使屏幕关闭且手机正在睡眠,也能使服务正常工作。我的问题是我正在使用警报管理器定期唤醒CPU,有时候,经常发生该过程只是停止更新。你能帮帮我吗?

这是我的服务代码:

public class NotificationService extends Service {
static String updateOnWifi;
SharedPreferences sharedpreferences;
String url;
String firstEventDescription = "Zatial ziadna nehoda";
String secondEventDescription = "Zatial ziadna nehoda";
String mp3Link = "false";
static int NOTIFICATION = 10002;
NotificationManager nManager;
private Handler mHandler = new Handler();
private Timer mTimer = null;
MediaPlayer mediaPlayer;
boolean vibrate;
boolean updateWiFi;
boolean updateMe;
private PowerManager.WakeLock wl;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //Toast.makeText(this, "Updating", Toast.LENGTH_LONG).show();

    if (mTimer != null) {
        mTimer.cancel();
    } else {
        mTimer = new Timer();
    }
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");
    wl.acquire();
    sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
    url = sharedpreferences.getString("url", "http://5.9.44.5/waze/appjson.php");
    Log.d("tag","new url "+url);
    int updateInterval = sharedpreferences.getInt("UpdateTimeout", 20);
    updateWiFi = sharedpreferences.getBoolean("Wifi", false);
    vibrate = sharedpreferences.getBoolean("Vibrate", true);
    boolean run = sharedpreferences.getBoolean("Running", false);
    if (run) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, updateInterval);
        Intent i1 = new Intent(NotificationService.this, NotificationService.class);
        PendingIntent pi = PendingIntent.getService(NotificationService.this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        new DownloadJSON().execute();
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
    }
    else{
        stopSelf();
    }
    //mTimer.scheduleAtFixedRate(new RepeatTask(), 0, updateInterval * 1000);
    return START_STICKY;
}

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Downloading...").setContentText(firstEventDescription).setOngoing(true);
    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    //Toast.makeText(this, "Cancelling", Toast.LENGTH_LONG).show();
    if (mediaPlayer != null) {
        mediaPlayer = null;
    }
    if (nManager != null) {
        nManager.cancel(NOTIFICATION);
    }
    mTimer.cancel();
}

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {

        showNotification();
        String abc = NetworkUtil.getConnectivityStatusString(NotificationService.this);
        Log.d("Tag", "provider: " + abc);
        if (abc.equalsIgnoreCase("mobile") || updateWiFi) {
            updateMe = true;
            showNotification();
        } else {
            updateMe = false;
            if (nManager != null) {
                nManager.cancel(NOTIFICATION);
            }
        }
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if (updateMe) {
            // Retrieve JSON Objects from the given URL address
            JSONObject jsonobject = JSONfunctions
                    .getJSONfromURL(url);
            if (jsonobject == null) {
                url = "http://5.9.44.5/waze/appjson.php";
            } else {
                try {
                    firstEventDescription = jsonobject.getString("text");
                    Log.d("Tag","First event: "+firstEventDescription);
                    if (firstEventDescription.equalsIgnoreCase("false")) {
                        firstEventDescription = secondEventDescription;
                    }
                    else {
                        secondEventDescription = firstEventDescription;
                    }
                    url = jsonobject.getString("url");
                    mp3Link = jsonobject.getString("mp3");
                    Log.d("Tag","url from server: " +url + " Notification display: " + firstEventDescription);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("url", url);
        editor.apply();
        if (!mp3Link.equalsIgnoreCase("false")) {
            showNotification();
            if (vibrate) {
                Vibrator v = (Vibrator) NotificationService.this.getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(750);
            }
            mediaPlayer = MediaPlayer.create(NotificationService.this, Uri.parse(mp3Link));
            if (mediaPlayer != null) {
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                        }
                    }
                });
            }
            mp3Link = "false";
        }
        wl.release();
    }
}

class RepeatTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                new DownloadJSON().execute();
            }

        });
    }

}

}

0 个答案:

没有答案