在Android中如何运行后台服务?

时间:2013-04-26 05:16:10

标签: java android android-intent

你能否告诉我在运行BackGround Service的代码中犯了什么错误。是否有任何其他代码可用于运行BackGround服务。 以下程序是否正确....如何在android中运行后台服务?

FrontEnd.java:
*****************

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FrontEnd extends Activity implements OnClickListener {

    private Button btnStartService, btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frontend);

        bindComponents();
        addListener();
        init();
    }

    private void bindComponents() {
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopService = (Button)findViewById(R.id.btnStopService);
    }

    private void addListener() {
        btnStartService.setOnClickListener(this);
        btnStopService.setOnClickListener(this);
    }

    private void init() {

    }

    public void onClick(View view) {
        Intent mIntent = new Intent(this,BackEndService.class);
        System.out.println("------------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<");
        switch (view.getId()) {
        case R.id.btnStartService:
            startService(mIntent);
            break;
        case R.id.btnStopService:
            stopService(mIntent);
            break;
        default:
            break;
        }
    }
}

******************************************************************************************************************

BackEndService.java
*********************

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BackEndService extends Service{

    private static final String tag = "Panacea";

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(tag, "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(tag, "onCreate");

        Notification notification = new Notification(R.drawable.launcher, getText(R.string.app_name),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, GmaTestApp01Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "BackGround Service", "Project is running", pendingIntent);
        startForeground(1, notification);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(tag, "onStart startId=" + startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(tag, "onStartCommand startId=" + startId);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(tag, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(tag, "onDestroy");
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }
}

*******************************************************************************************************************
frontend.xml
***************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
   >



    <Button
        android:id="@+id/btnStartService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start_service"
         />



    <Button
        android:id="@+id/btnStopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/stop_service" />

</LinearLayout>

Screenshot1

Screenshot2 更新:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends Activity
{



    Integer[] imageIDs = {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e,
            R.drawable.f,
            R.drawable.g,
            R.drawable.h,
            R.drawable.i,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, 
            View v, int position, long id) 
            {                
                /*Toast.makeText(getBaseContext(), 
                        "pic" + (position + 1) + " selected", 
                        Toast.LENGTH_SHORT).show();*/
                int pos= position + 1;

                if(pos == 1)
                {
                     Intent intent = new Intent("com.project.GmaTestApp01Activity");
                     startActivity(intent);
                }
                else if(pos == 2)
                {
                     Intent intent = new Intent("com.project.FrontEnd");
                     startActivity(intent);
                }
                else if(pos == 9)
                {
                    Intent intent = new Intent("com.project.UserProfile");
                    startActivity(intent);
                }
                else
                {
                    Toast.makeText(getBaseContext(),"Coming Soon!", Toast.LENGTH_SHORT).show();
                }

            }
        });   

        gridView.setOnTouchListener(new OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_MOVE){
                    return true;
                }
                return false;
            }

        });
    }

    public class ImageAdapter extends BaseAdapter 
    {
        private Context context;

        public ImageAdapter(Context c) 
        {
            context = c;
        }

        //---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }

        //---returns the ID of an item--- 
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }    
}

2 个答案:

答案 0 :(得分:1)

如果BackEndService服务未运行,可能因为您忘记在清单文件中提及它。如果有,请添加以下内容。

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

   <activity ....>
    ...
    </activity>

    <service android:name=".BackEndService"></service>
    ....
    </application>

您的代码似乎是正确的。

答案 1 :(得分:0)

自Android 8开始,运行无通知的后台服务将不起作用。