android:如何启动服务

时间:2014-10-14 07:16:28

标签: android service alarmmanager smsmanager

我有一个应用程序,它会在特定时间后发送自动短信。我希望它始终在后台运行,当我重新启动手机时,它应该自动启动该过程。当我使用Activity扩展它时它工作正常。请告诉我应该如何使用服务启动它。

服务类代码

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;
}

}

第二类代码

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文件

<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>

3 个答案:

答案 0 :(得分:1)

您需要像这样创建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);
    }
}

并在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" />

答案 1 :(得分:0)

尝试这样的事情,

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;
      }
    }

}

这是广播接收器

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);

      }
}

其中HandlerService是服务类。为服务创建新类并将其注册到清单文件中。在应用程序节点中添加这些行。

<receiver android:name="come.code.BootCompleteReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

其中come.code是BootCompleteReceiver类的包

答案 2 :(得分:0)

您可能希望使用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);
      }
    }

只需在onCreate或onResume()中调用bindServices(),在这种情况下,您可能希望在onPause()

中取消绑定它

请注意,您可以根据需要多次调用StartService(),每次只调用onStartCommand()