android双后台服务,消息通知类(service2)

本文介绍了一个名为Service2的Android服务示例,该服务能够启动另一个服务Service1,并在设备上显示通知。Service2还包含了一些生命周期回调方法的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.service.demo;


import java.util.List;


import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
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.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
/**
 * 
 * @author 掌缘生灭
 *
 */
public class Service2 extends Service {
private String TAG = getClass().getName();
private String Process_Name = "com.example.servicetest2:service1";



/**
*启动Service1 
*/
private StrongService startS1 = new StrongService.Stub() {


@Override
public void stopService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service1.class);
getBaseContext().stopService(i);
}


@Override
public void startService() throws RemoteException {
Intent i = new Intent(getBaseContext(), Service1.class);
getBaseContext().startService(i);

}
};

@Override
public void onTrimMemory(int level){
Toast.makeText(getBaseContext(), "Service2 onTrimMemory..."+level, Toast.LENGTH_SHORT)
.show();
keepService1();
}

public void onCreate() {
Toast.makeText(Service2.this, "Service2 onCreate...", Toast.LENGTH_SHORT).show();
keepService1();






new Thread()
{
int i=0;
public void run()
{
while(true)
{


ServiceUtils.showNotification(Service2.this,"测试标题","测试内容","1234");
try 
{
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
}.start();
}


/**
* @获取默认的pendingIntent,为了防止2.3及以下版本报错
* @flags属性:  
* 在顶部常驻:Notification.FLAG_ONGOING_EVENT  
* 点击去除: Notification.FLAG_AUTO_CANCEL 
*/
public PendingIntent getDefalutIntent(int flags){
PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
return pendingIntent;
}


/**
* 判断Service1是否还在运行,如果不是则启动Service1
*/
private  void keepService1(){
boolean isRun = ServiceUtils.isProessRunning(Service2.this, Process_Name);
if (isRun == false) {
try {
Toast.makeText(getBaseContext(), "重新启动 Service1", Toast.LENGTH_SHORT).show();
startS1.startService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}


@Override
public IBinder onBind(Intent intent) {
return (IBinder) startS1;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值