android使用Service在后台运行

android使用Service在后台运行

public void useForeground(CharSequence tickerText, String currSong) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
/* Method 01

 * this method must SET SMALLICON! 
 * otherwise it can't do what we want in Android 4.4 KitKat, 
 * it can only show the application info page which contains the 'Force Close' button.*/  
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(PlayService.this)  
        .setSmallIcon(R.drawable.ic_launcher)  
        .setTicker(tickerText)  
        .setWhen(System.currentTimeMillis())  
        .setContentTitle(getString(R.string.app_name))  
        .setContentText(currSong)  
        .setContentIntent(pendingIntent);  
Notification notification = mNotifyBuilder.build();  

/* Method 02  
Notification notification = new Notification(R.drawable.ic_launcher, tickerText, 
        System.currentTimeMillis()); 
notification.setLatestEventInfo(PlayService.this, getText(R.string.app_name), 
        currSong, pendingIntent); 
*/  

startForeground(NOTIFY_ID, notification);  

}

1
2
3
4
5
6
7
8
9
## android黑屏后保持Service运行

```java
private PowerManager.WakeLock wakeLock = null;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MyService.class.getName());
wakeLock.acquire();
//需要权限
<uses-permission android:name="android.permission.WAKE_LOCK" />