确定在服务中单击了哪个按钮

时间:2014-04-07 05:57:52

标签: android

有一个简单的服务运行,我有一些按钮,每个做不同的事情(我也想要它们)。我不知道如何让服务知道按下了哪个按钮。当我按下按钮时我想要一个服务启动,但是根据按下哪个按钮它需要做一些不同的事情。

服务类

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    NotificationCompat.Builder mBuilder;
    private int i = 1;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onCreate() {
        Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

    } 

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        i++;
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // Do task depend on cliked view
        String clickedView = intent.getStringExtra("clicked_on");
        if ("BUTTON1".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("One Added!");
        } else if ("BUTTON2".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("Two Added!");
        }else if ("BUTTON3".equals(clickedView)) {
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("One Subtracted!");
        }else{
            mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Egg")
            .setContentText("Woo Lets Eat!!");
        }

        Intent resultIntent = new Intent(this, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(i, mBuilder.build());

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

    }
}

主要活动

导入android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View;

公共类MainActivity扩展了Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

// Start the  service
public void startNewService(View view) {
    Intent serviceIntent = new Intent(this, MyService.class);
    if (view.getId() == R.id.button1) {
        serviceIntent.putExtra("clicked_on", "BUTTON1");
    } else if (view.getId() == R.id.button2) {
        serviceIntent.putExtra("clicked_on", "BUTTON2");
    } else if (view.getId() == R.id.button3) {
        serviceIntent.putExtra("clicked_on", "BUTTON3");
    } else {
        serviceIntent.putExtra("clicked_on", "BUTTON4");
    }
    startService(serviceIntent);
}

// Stop the  service
public void stopNewService(View view) {     
    stopService(new Intent(this, MyService.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

MAIN XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="@color/LightSalmon"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:text="@string/add_one" 
        android:textColor="@color/White"
        android:onClick="startNewService"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_two" 
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sub_one" 
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/make"
        android:layout_marginTop="20dp"
        android:textColor="@color/White"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cnt"
        android:layout_marginTop="120dp"
        android:textColor="@color/LightSalmon"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

2 个答案:

答案 0 :(得分:1)

您应该使用AsynTask代替Service

但这是您当前方法的解决方案(但我会选择AsyncTask)

修改startNewService,它将读取点击按钮的id并发送到Service for intent extra。

public void startNewService(View view) {

    Intent serviceIntent = new Intent(this, MyService.class);
    // Read id of view and put extra.
    if (view.getId() == R.id.button1) {
        serviceIntent.putExtra("clicked_on", "BUTTON1");
    } else if (view.getId() == R.id.button2) {
        serviceIntent.putExtra("clicked_on", "BUTTON2");
    }
    startService(serviceIntent);
}

现在覆盖有意图为param的Service onStartCommand。你可以阅读额外的和做任务取决于那。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // Do task depend on cliked view
    String clickedView = intent.getStringExtra("clicked_on");
    if ("BUTTON1".equals(clickedView)) {
        // Do task for button 1
    } else if ("BUTTON2".equals(clickedView)) {
        // Do task for button 2
    }
    return START_STICKY;
}

答案 1 :(得分:-1)

请考虑以下事项:

  1. 应用启动后启动服务
  2. 让服务听2广播操作
  3. 在某个按钮上单击“通过特定操作向服务发送广播”