Android服务不起作用

时间:2015-07-02 03:43:13

标签: android

我的应用程序遵循下一个方案...

javax.validation.*

  • 线程重复睡眠(5000)
  • 如果thread是sleep(),则startService()

1.[Main Activity]

2.[Service.class] sendBroadcast()

线程工作干净,但服务不会被呼叫。

我在Manifest.xml中注册

我创建了BroadcastReceiver动态。

的Manifest.xml

3.[Main Activity - BroadcastReceiver] Toast()

MainActivity.java

<application
    android:allowBackup="true"
    android:icon="@mipmap/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:name=".Service"
             android:enabled="true" />
</application>

Service.class

public class MainActivity extends ActionBarActivity implements Runnable {
Thread mThread;
Boolean mSleep = false;

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

    Log.d("Activity", "onCreate()");
}
@Override
protected void onStart() {
    super.onStart();
    Log.d("Activity", "onStart()");

    mThread = new Thread(this);
    mThread.start();
}

@Override
public void run() {
    Log.d("Thread", "run()");

    while(true) {
        try {
            mThread.sleep(5000);
        } catch (InterruptedException e) {
            //empty
        }
        Log.d("Thread", "sleep");
        mSleep = true;
        Log.d("Thread1", mSleep.toString());
        Context context = getApplicationContext();
        context.startService(new Intent(MainActivity.this, Service.class));

        mSleep = false;
        Log.d("Thread2", mSleep.toString());
    }
}   

@Override
protected void onResume() {
    super.onResume();
    Log.d("Activity", "onResume()");

    Log.d("Is it main thread?", mThread.currentThread().getName());

    IntentFilter filter = new IntentFilter();
    //No Action
    registerReceiver(mBroadcastReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    Log.d("Activity", "onPause()");

    unregisterReceiver(mBroadcastReceiver);
}

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "sleep sleep sleep", Toast.LENGTH_SHORT).show();
    }
};
}

1 个答案:

答案 0 :(得分:0)

检查你导入的包,这里的服务不是android.app.Service

context.startService(new Intent(MainActivity.this, Service.class));