Service

部署运行你感兴趣的模型镜像
public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private Button startService,redirectButton;

public static MainActivity mainActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService=(Button)findViewById(R.id.startButton);
redirectButton=(Button)findViewById(R.id.redirectId);
Log.e("Main", "onCreate======================>") ;
startService(new Intent("com.test.android.SERVICE"));

}


public void onAttachedToWindow () {
System.out.println("Page01 -->onAttachedToWindow");
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}







@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch(v.getId())
{
case R.id.redirectId:
break;
}
}





@Override
protected void onStart()
{


super.onStart();
mainActivity=this;
Log.e("Main", "onStart======================>") ;
}


@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("Main", "onStop======================>") ;
}


@Override
protected void onResume() {
// TODO Auto-generated method stub


super.onResume();
Log.e("Main", "onResume======================>") ;
if(!SipService.isOnForeground)
this.onStop();
}




}


======

public class SecondActivity extends Activity implements OnClickListener{

private Button closeButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
closeButton=(Button)findViewById(R.id.closeId);
closeButton.setOnClickListener(this);
}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.closeId:
finish();
if(!SipService.isOnForeground)
{
Log.e("SecondActivity", "begin to close Main");

Log.e("mainActivity", "mainActivity="+MainActivity.mainActivity.isFinishing());
MainActivity.mainActivity.onStop();
}

break;
default:break;
}

}


}


==================
public class SipService extends Service{

private ActivityManager activityManager;
private String packageName;

//应用是否运行在前端
public static boolean isOnForeground=true;

private static Handler handler;




//休眠唤醒锁
private static PowerManager.WakeLock mWakeLock = null;


//唤醒加锁
public static void acquireWakeLock(Context context)
{
if (mWakeLock == null)
{
Log.i("", "Acquiring wake lock");
PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
context.getClass().getCanonicalName());
mWakeLock.acquire();
}
}


@Override
public void onCreate()
{
super.onCreate();
Log.e("SipService", "------------->service---onCreate!!!");

//acquireWakeLock(this.getApplicationContext());
acceptHandler();

Timer timer=new Timer();
timer.schedule(task,5000,60000);

// audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
// audioManager.setMode(AudioManager.MODE_IN_CALL);
// Log.e("SipService", "onCreate ----------> AudioManager.setMode(AudioManager.MODE_IN_CALL)");
// SystemUtil.setMicrophoneMute(false);
// SystemUtil.getSpeakerphoneVolume();
}



TimerTask task=new TimerTask() {

@Override
public void run() {
// TODO Auto-generated method stub
Message message=new Message();
message.what=1;
SipService.handler.sendMessage(message);
}
};



@Override
public void onDestroy()
{
super.onDestroy();
Log.e("sipService", "------------->service---onDestroy!!!");
//releaseWakeLock();
// audioManager.setMode(AudioManager.MODE_NORMAL);
// Log.e("SipService", "onStop ----------> AudioManager.setMode(AudioManager.MODE_NORMAL)");
}

@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}




//释放唤醒锁
public static void releaseWakeLock()
{
if (mWakeLock != null && mWakeLock.isHeld())
{
Log.i("", "release wake lock");
mWakeLock.release();
mWakeLock = null;
}
}




//判断 应用是否运行在前端
private boolean isAppOnForeground() {
// Returns a list of application processes that are running on the device
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) return false;
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}


@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

private void acceptHandler(){
Handler accHandler= new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{

case 1:
{
activityManager = (ActivityManager)SipService.this.getSystemService(Context.ACTIVITY_SERVICE);
packageName =SipService.this.getPackageName();

//应用是否运行在前端
isOnForeground=isAppOnForeground();
Log.e("SipService", "isOnForeground="+isOnForeground);

//如果在前台运行
if(!isOnForeground)
{
Bundle bundle = new Bundle();
Intent intent = new Intent();
intent.putExtras(bundle);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setClass(getApplicationContext(),SecondActivity.class);
startActivity(intent);
}
break;
}
}
}
};

SipService.handler=accHandler;
}




}


============
public class SipServiceManager extends BroadcastReceiver{

@Override
public void onReceive(Context arg0, Intent arg1) {
Log.e("","-------BroadcastReceiver--> " + arg1.getAction());

//开机
if(arg1.getAction().toString().equals(Intent.ACTION_BOOT_COMPLETED)){
arg0.startService(new Intent("cn.zte.sip.SERVICE"));
}
//关机
else if(arg1.getAction().toString().equals(Intent.ACTION_SHUTDOWN)){
arg0.stopService(new Intent("cn.zte.sip.SERVICE"));
}
}
}


============
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:text="启动Service"
android:id="@+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>


<Button
android:text="转向按钮"
android:id="@+id/redirectId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>


</LinearLayout>


==================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>


<Button
android:text="转向Main界面"
android:id="@+id/redirectId2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>


<Button
android:text="关闭本界面"
android:id="@+id/closeId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>

======

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.android"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">

<service android:name="com.test.android.SipService">
<intent-filter>
<action android:name="com.test.android.SERVICE" />
</intent-filter>
</service>

<receiver android:name="com.test.android.SipServiceManager" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>

<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" android:screenOrientation="landscape" />

</application>


</manifest>

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

08-10
### Service的生命周期和状态 ServiceAndroid系统中可以分为两种主要状态:启动状态和绑定状态。当一个Service被启动后,它会在后台长时间运行,即使启动它的组件已经被销毁,Service仍然可以继续运行[^2]。如果一个Service既被启动又被绑定,那么它会同时处于这两种状态。 ### Service的生命周期方法 自定义的Service需要继承`Service`基类,并且通常需要重写一些生命周期方法来实现特定的功能: - `onCreate()`:当Service第一次创建时调用。如果Service已经存在,则不会调用此方法。 - `onStartCommand(Intent intent, int flags, int startId)`:当其他组件通过调用`startService()`方法请求启动Service时调用。在这个方法里可以处理长时间运行的操作。 - `onBind(Intent intent)`:当其他组件通过调用`bindService()`方法绑定到Service时调用。该方法返回一个`IBinder`接口,允许客户端与Service进行通信。 - `onUnbind(Intent intent)`:当所有绑定到Service的客户端都解绑后调用。 - `onDestroy()`:当Service不再使用并被销毁时调用。这是释放资源的好时机。 ### 启动状态下的Service 当一个Service通过调用`startService()`方法启动时,它进入启动状态。在这种状态下,Service独立于启动它的组件运行,直到它自己停止或被系统终止。要停止这样的Service,可以在Service内部调用`stopSelf()`方法,或者从外部组件调用`stopService()`方法[^1]。 ### 绑定状态下的Service 当组件通过调用`bindService()`方法绑定Service时,Service进入绑定状态。此时,组件可以通过`ServiceConnection`对象获取到Service提供的`IBinder`对象,从而与Service进行交互。绑定状态下的Service可以被多个组件绑定,只有当所有绑定的组件都解绑后,Service才会被销毁[^3]。 ### Service的声明 无论哪种类型的Service,都需要在`AndroidManifest.xml`文件中声明。声明格式如下: ```xml <service android:name=".Demo2Service" /> ``` 其中`.Demo2Service`是你的Service类名[^2]。 ### Service的绑定过程 为了与Service进行交互,组件需要创建一个`ServiceConnection`实例,并实现其`onServiceConnected()`和`onServiceDisconnected()`回调方法。例如: ```java private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 这里 IBinder类型的service 就是我们要绑定的那个service // 通过这个serviceActivity就可以调用MyBindService.MyBinder中的方法 } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "onServiceDisconnected: "); } }; ``` 然后,组件可以通过调用`bindService()`方法来绑定Service,并在不需要时调用`unbindService()`方法来解绑[^5]。 ### Service的应用场景 Service非常适合用来执行那些不需要用户界面但需要长时间运行的任务。比如播放音乐、下载文件、处理网络请求等。此外,Service还可以与其他组件进行交互,包括跨进程通信(IPC)[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值