[英]android: how to start a service
I have an app which sends auto sms after a specific time.I want it to always run in the background and when I restart the phone it should start the process automatically. 我有一个可以在特定时间后发送自动短信的应用程序,我希望它始终在后台运行,并且当我重启手机时它应该自动启动该过程。 It worked fine when I extend it with Activity.
当我用Activity扩展它时,它工作得很好。 Kindly tell me how should I start it with Service.
请告诉我如何从服务开始。
the code of service class 服务等级代码
public class MainActivity extends Service {
@Override
public void onCreate() {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
startLocationTracking();
}
private void startLocationTracking()
{
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1=new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exjfkd"+e);
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND,5);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*180, sender1);
System.out.println("set timer");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
code of second class 二级代码
public class AlarmReceiver extends BroadcastReceiver{
long time = 180 * 1000;
long distance = 10;
@SuppressLint("NewApi")
@Override
public void onReceive(final Context context, Intent intent) {
System.out.println("alarm receiver....");
LocationManager locationManager = (LocationManager)context
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, time,
distance, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
String phoneNo = "+96987978";
String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
Toast.makeText(context, "message sent", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
}
};
}
AndroidManifest file AndroidManifest文件
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:enabled="true"
android:name="com.example.locationupdates.services.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
<receiver android:name="com.example.locationupdates.AlarmReceiver" >
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
You need to create Boot Receiver
like this: 您需要这样创建
Boot Receiver
:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, YourService.class);
context.startService(myIntent);
}
}
And add this in your AndroidManifest.xml
并将其添加到您的
AndroidManifest.xml
<!-- Declaring broadcast receiver for BOOT_COMPLETED event -->
<receiver android:name=".MyReceiver " android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Try something like this, 试试这个
public class HandlerService extends Service
{
private final IBinder mBinder = new MyBinder();
@Override
public IBinder onBind( Intent arg0 )
{
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//your stuff
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
Log.d( "oncreated", "oncreated" );
}
@Override
public void onDestroy() {
}
public class MyBinder extends Binder {
HandlerService getService() {
return HandlerService.this;
}
}
}
This is the broadcast receiver 这是广播接收器
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("BootCompleteReceiver", "BootCompleteReceiver");
Intent service = new Intent(context, HandlerService.class);
context.startService(service);
}
}
where HandlerService is the service class. 其中HandlerService是服务类。 Create new class for the service and register it in the manifest file.
为服务创建新的类,并将其注册在清单文件中。 Add those lines inside the application node.
将这些行添加到应用程序节点中。
<receiver android:name="come.code.BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
where come.code is the package of BootCompleteReceiver class 其中come.code是BootCompleteReceiver类的包
You may want to use a ServiceConnection to check when your service is really starting and bind it if you want to keep interacting with it 您可能想使用ServiceConnection来检查您的服务何时真正启动,并且如果您想继续与之交互,请绑定它
private Service mService;
private ServiceConnection mServiceConnexion = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
if (mService == null) {
mService = (Service) ((Service.Binder) binder).getServiceInstance();
}
Intent intent = new Intent(ActivityPlayer.this, ServiceStreaming.class);
startService(intent);
}
};
private void bindService() {
if (mServiceConnexion != null) {
bindService(new Intent(Activity.this, Service.class), mServiceConnexion, Context.BIND_AUTO_CREATE);
}
}
Just call bindServices() in onCreate or onResume(), in this case you would want to unbind it in onPause() 只需在onCreate或onResume()中调用bindServices(),在这种情况下,您将需要在onPause()中解除绑定
Note that you can call StartService() as many times as you want it does't matter, it will just call onStartCommand() each time 请注意,您可以多次调用StartService()没关系,每次都只会调用onStartCommand()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.