【问题标题】:how to run services using broadcast receiver如何使用广播接收器运行服务
【发布时间】:2012-05-10 10:55:32
【问题描述】:

如何使用广播接收器启动后台服务。为相机锁定操作提供了一项服务,但一段时间后功能无法正常工作。服务在安卓设备上运行。但是 onstartcommand 中的服务方法不起作用。

使用了 action.user_present 但它不起作用。

 public class camerareceiver extends BroadcastReceiver{ 
public static String TESTACT_S = "android.intent.action.USER_PRESENT"; 
     @Override
     public void onReceive(Context context, Intent intent) {
     if(intent.getAction().equals(TESTACT_S))
      { context.startService(newIntent("com.simsys.camera.ServiceTemplate")); } }

【问题讨论】:

  • 什么问题?显示相关代码和Logcat。
  • 使用了 action.user_present 但它不起作用 .public class camerareceiver extends BroadcastReceiver{ public static String TESTACT_S = "android.intent.action.USER_PRESENT"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(TESTACT_S)){ context.startService(new Intent("com.simsys.camera.ServiceTemplate")); } } 在 log cat 中没有显示错误。但是在运行服务时,摄像头正在工作而不是锁定摄像头。

标签: android service broadcastreceiver


【解决方案1】:

从 BroadcastReceiver 启动服务为:

public class CamReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
   Toast.makeText(context, "ACTION_USER_PRESENT",  Toast.LENGTH_LONG).show();
 context.startService(new Intent(context,ServiceTemplate.class));
}
}
}

在清单中:

<receiver android:name= ".CamReceiver">
           <intent-filter>
             <action android:name="android.intent.action.USER_PRESENT"/>
           </intent-filter>
        </receiver>

【讨论】:

  • 使用了 action.user_present 但它不起作用 .public class camerareceiver extends BroadcastReceiver{ public static String TESTACT_S = "android.intent.action.USER_PRESENT"; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(TESTACT_S)){ context.startService(new Intent("com.simsys.camera.ServiceTemplate")); } }
  • 查看我的编辑答案,如果没有得到解决,请发布您的 catlog 堆栈跟踪和代码
  • com.simsys.camera.ServiceTemplate 你的包或其他应用程序?
  • com.simsys.camera 是我的包名,服务模板是服务名
  • @user1345747 :等待它肯定会起作用,因为我们正在以正确的方式进行操作。我已经在广播接收器中添加了一个 toast,所以当你在设备上进行测试时它是否会出现?
猜你喜欢
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多