Mas*_*mad 11 android android-intent android-service android-alarms android-backup-service
Status:---
我同样接受Karakuri的和沙拉德Mhaske的答案,但由于沙拉德Mhaske回答之后的赏金的开始,赏金应该去他.
第2 部分:第2 部分持续foreGround android服务,由UI启动,也在睡眠模式下工作,也从手机重启开始
在stack overflow
,只有一个答案可以接受.我认为这两个答案都是可以接受的,但必须选择一个(我随机选择).
观众被邀请上/下投票答案/问题,以欣赏努力!.我赞成Karakuri的答案来弥补声誉.
Scenario:---
我想让用户单击开始/停止按钮并从UI活动启动/停止服务.我已经制作了用户界面,所以不关心它.但只是按钮点击事件的逻辑.
难道不希望该服务绑定到用户界面活动.如果活动关闭,服务应继续运行.
想要尽最大努力保持服务的持久性并且在任何情况下都不会停止.将它赋予最大的权重并运行它,ForGroundSerice
因为它具有更高的重要性层次.(希望没问题?)
除非我的应用程序用户界面点击了停止按钮,否则不要让它停止(或者应该重新启动)即使android回收内存.我和手机用户都知道了.这项服务至关重要.即使在睡觉.
details =我的应用程序执行一些操作,为用户提供的时间(通常为15分钟)休眠,唤醒并再次执行操作.这永远不会结束)
如果我需要AlarmManager
,如何实现?或任何其他方式?或者只是把操作放在while loop and sleep for 15 minuts
最后?
启动服务时(通过单击"开始"按钮).它应该输入一个条目,以便在手机重启时自动启动.
QUESTION:---
Primary Question:
只是无法为场景获得最佳策略 ......并且还会停留在一小段代码上,哪些代码可以使用以及如何使用.
来自stackoverflow.com的问题,developer.android.com和一些谷歌搜索结果,但无法在集成中实现.
请阅读请求部分.
Secondary Question:
我的代码中的注释是那些小问题.
Research and Code:---
战略:
want this to happen every time the user opens the UI.
//Start Button:-----
//check if ForGroundService is running or not. if not running, make var/settings/etc "serviceStatus" as false
<-------(how and where to stare this and below stated boolean?)
//start ForGroundService
<-------(how?)
//make "SericeStatus" as true
//check if "ServiceStartOnBoot" is false
//Put ForGroundService to start on boot -------(to make it start when ever the phone reboots/restarts)
<-------(how?)
//make "ServiceStartOnBoot" as true
// the boolean can also be used to check the service status.
//Stop Button:------
//makes SericeStatus and ServiceStartOnBoot as false
//stops service and deletes the on boot entry/strategy
Run Code Online (Sandbox Code Playgroud)
用于启动/停止服务的Activity UI类:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//some button here to start / stop and their onClick Listners
Intent mySericeIntent = new Intent(this, TheService.class);
}
private void startMyForGroundService(){
startService(mySericeIntent);
}
private void stopMyForGroundSerice(){
stopService(mySericeIntent);
/////// is this a better approach?. stopService(new Intent(this, TheService.class));
/////// or making Intent mySericeIntent = new Intent(this, TheService.class);
/////// and making start and stop methods use the same?
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
Run Code Online (Sandbox Code Playgroud)
服务类:
public class TheService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, new Notification());
////// will do all my stuff here on in the method onStart() or onCreat()?
return START_STICKY; ///// which return is better to keep the service running untill explicitly killed. contrary to system kill.
///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY
//notes:-// if you implement onStartCommand() to schedule work to be done asynchronously or in another thread,
//then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it
}
@Override
public void onDestroy() {
stop();
}
public void stop(){
//if running
// stop
// make vars as false
// do some stopping stuff
stopForeground(true);
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
Run Code Online (Sandbox Code Playgroud)
Menifest文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapp.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="com.example.myapp.SettingsActivity"
android:label="@string/title_activity_settings" >
</activity>
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
References:---
Android - 为服务实现startForeground?指点答案1,示例代码.
http://developer.android.com/guide/components/services.html
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/training/run-background-service/create-service.html不是我提供的.
http://developer.android.com/guide/components/processes-and-threads.html我的研究起点
Requests:---
我认为这个问题对于大多数处理服务的人来说都是正常的做法.在该愿景中,请仅回答您是否具有该方案的经验,并且能够以最大样本代码作为完整版本全面解释方面和策略,以便它也将对社区有所帮助.
对答案进行上下(有责任)投票,因为对我而言,他们分享了他们的观点,时间和经验,并帮助我和社区.
问:要尽最大努力使服务持久并且在任何情况下都不会停止。将给予它最大的权重并将其作为 ForGroundSerice 运行,因为它具有更高的重要性层次结构。(希望这样可以吗?)
答:您需要使用 START_STICKY Intent 标志来启动服务。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)
问:如果我需要AlarmManager,如何实现?或者任何其他方式?或者只是将操作放入永无休止的 while 循环中并在最后休眠 15 分钟?
答:执行某个任务后,您需要在服务中注册 Alarmmanager 。//在服务中注册警报管理器。
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);
Run Code Online (Sandbox Code Playgroud)
//现在有一个广播接收器来接收这个意图。
class Alarmreceiver extends Broadcastreceiver
{
//u can to task in onreceive method of receiver.
}
Run Code Online (Sandbox Code Playgroud)
//在清单中注册此类以用于警报接收器操作。
问:当服务启动时(通过单击启动按钮)。它应该创建一个条目,以便在手机重新启动时自动启动。
答:使用广播接收器来监听 onboot 完成的意图。
public class StartAtBootServiceReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
try {
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(), LicensingService.class.getName());
ComponentName service = context.startService(new Intent().setComponent(comp));
if (null == service){
// something really wrong here
//Log.Write("Could not start service " + comp.toString(),Log._LogLevel.NORAML);
}
}
else {
//Log.Write("Received unexpected intent " + intent.toString(),Log._LogLevel.NORAML);
}
} catch (Exception e) {
//Log.Write("Unexpected error occured in Licensing Server:" + e.toString(),Log._LogLevel.NORAML);
}
}
}
Run Code Online (Sandbox Code Playgroud)
//需要在manifest.xml文件中为Action_BOOTCOMPLETED意图注册此接收器 希望这可以帮助您清除问题:)
归档时间: |
|
查看次数: |
5759 次 |
最近记录: |