gpt4 book ai didi

android - 在android平台上启动服务

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:50 25 4
gpt4 key购买 nike

我正在使用 startService(Intent intent) 方法启动服务。当我调用此函数时,它会到达服务的 onCreate,但无法调用 onStartCommand。这是我的代码——

@Override
public void onReceive(Context context, Intent intent) {
// Send a text notification to the screen.
Log.e("mudit", "Action: " + intent.getAction());

try {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
Log.e("mudit", "getType: " + info.getType());
Log.e("mudit", "isConnected: " + info.isConnected());
if (info.isConnected()) {

Intent newinIntent = new Intent(context, service.class);
context.startService(newinIntent);
}

} catch (Exception e) {
e.printStackTrace();
Intent newinIntent = new Intent(context, service.class);
context.stopService(newinIntent);

}

}

服务代码--

package com.android.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class service extends Service {

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

@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}

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

Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
}

}

list .xml --

<receiver class=".AReceiver" android:name=".AReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service class=".service" android:name=".service"
android:enabled="true" android:icon="@drawable/icon">
</service>

最佳答案

  1. Unbound Service: it runs in the background indefinitely even started activity with service ends also.
  2. Bound Service : it will run till life time of activity.

Activity can start service via startService() and it will stop via stopService(). If activity wants to interact with service, it can use bindService().

First onCreate() is called, after onStartCommand is called with the intent data provided by the activity.

Source

关于android - 在android平台上启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2301057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com