繁体   English   中英

Android-如何将数据从活动发送到服务?

[英]Android- How to send data from activity to service?

在我的应用程序中,我正在尝试将数据从我的MainActivity.class发送到名为bgservice.class的服务。 这是我的以下代码:

MainActivity.class:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Intent serviceIntent = new Intent(bgservice.class.getName());
  serviceIntent.putExtra("UserID", "123456");
  this.startService(serviceIntent);
}

bgservice.class:

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

  String userID = intent.getStringExtra("userID");
  System.out.println(userID);
  Toast.makeText(this,userID, Toast.LENGTH_LONG).show();
  return START_STICKY;

}

但我没有在服务类中获取数据。 这些是我得到的以下错误:

02-25 09:05:41.166:E / AndroidRuntime(2633):

java.lang.RuntimeException:无法启动活动
ComponentInfo {com.microapple.googleplace / com.microapple.googleplace。 MainActivity}:java.lang.IllegalArgumentException:Service Intent必须是显式的:Intent {act = com.microapple.googleplace.bgservice(has extras)}

AndroidManifest.xml中:

     ...
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name=".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>
    <service android:enabled="true" android:name=".bgservice" />
</application>
....
Intent serviceIntent = new Intent(YourActivity.this, bgservice.class);
        serviceIntent.putExtra("UserID", "123456");
        this.startService(serviceIntent);

在你的服务中,

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

    String userID = intent.getStringExtra("UserID");

    //do something

    return START_STICKY;

}

这必须奏效。

这里:

 Intent serviceIntent = new Intent(bgservice.class.getName());

将String传递给Intent构造函数以创建Intent以启动Service。 Intent构造函数将String作为我们在AndroidManifest.xml添加的Action名称。

<service android:enabled="true" android:name=".bgservice">
<intent-filter >
        <action android:name="com.microapple.googleplace.bgservice" />
    </intent-filter>
</service>

现在使用com.microapple.googleplace.bgservice作为操作名称来创建Intent:

      Intent serviceIntent = new Intent("com.microapple.googleplace.bgservice");
      serviceIntent.putExtra("UserID", "123456");
      this.startService(serviceIntent);

要么

使用Intent constrictor,它将Context作为第一个参数和我们想要作为第二个参数启动的组件名称:

  Intent serviceIntent = new Intent(this,bgservice.class);
  serviceIntent.putExtra("UserID", "123456");
  this.startService(serviceIntent);

并且还使用相同的密钥,用于在Intent中添加数据,当前使用UserID键添加值,但尝试使用userID键获取值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM