App保活,无声音乐保活

最近在做一个运动手环项目,需要不断的更新运动数据,并且在灭屏的状态下给用户推送来电和短信。大部分手机在App灭屏的状态下就会把App睡眠了,这样是推送不了短信的,用户不满意啊。后来发现播放音乐之类的灭屏也能播啊,那就假装咱也是音乐播放方应用吧。

1.Service的内容:

import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.smile.android.wristbanddemo.MainActivity;
import com.smile.android.wristbanddemo.R;

import java.util.List;

/**
 * 描述:
 * 保活
 * @author sxk
 * @date 2019/05/14
 */

public class LiveService2 extends Service {
    private final static String TAG = "PlayerMusicService";
    private MediaPlayer mMediaPlayer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
//        throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, TAG + "---->onCreate,启动服务");
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
        mMediaPlayer.setLooping(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //1.通知栏占用,不清楚的看官网或者音乐类APP的效果
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setTicker("Keep App alive")
                .setContentTitle("Keep "+getResources().getString(R.string.app_name)+" alive.")
                .setOngoing(true)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();
        /*使用startForeground,如果id为0,那么notification将不会显示*/
        startForeground(100, notification);

        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();
        return START_STICKY;
    }

    private void startPlayMusic() {
        if (mMediaPlayer != null) {
            Log.d(TAG, "启动后台播放音乐");
            mMediaPlayer.start();
        }
    }

    private void stopPlayMusic() {
        if (mMediaPlayer != null) {
            Log.d(TAG, "关闭后台播放音乐");
            mMediaPlayer.stop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPlayMusic();
        Log.d(TAG, TAG + "---->onCreate,停止服务");
        // 重启
        Intent intent = new Intent(getApplicationContext(), LiveService2.class);
        startService(intent);
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);
        List lists = am.getRunningAppProcesses();


        for (ActivityManager.RunningAppProcessInfo info : lists) {// 获取运行服务再启动
            System.out.println(info.processName);
            if (info.processName.equals(serviceName)) {
                isRunning = true;
            }
        }
        return isRunning;

    }
}

2.AndroidManifest.xml中注册service:

3.启动service

Intent intent = new Intent(this, LiveService2.class);
if (Build.VERSION.SDK_INT>=26) {
    startForegroundService(intent);
}else startService(intent);

 

你可能感兴趣的:(Android)