我想要一个没有任何GUI或活动的android应用程序。在我的情况下,我将只显示一个自定义Toast消息,这是我的要求。我正在给我的代码片段,即显示完成但没有期望的结果。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="rit.utility"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<service android:enabled="true" android:name="MyService"></service>
<receiver android:enabled="true" android:name="MyIntentReceiver">
<intent-filter>
<action android:name="MY_INTENT" />
</intent-filter>
</receiver>
</application>
public class MyIntentReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context _context, Intent _intent)
{
if(_intent.getAction().equals("MY_INTENT"))
{
_context.startService(new Intent(_context, MyService.class));
}
}
}
public class MyService extends Service
{
private final IBinder mBinder = new MyBinder();
public void onCreate()
{
super.onCreate();
createToast();
}
public void createToast()
{
TextView textView = new TextView(this);
textView.setBackgroundColor(Color.GRAY);
textView.setTextColor(Color.BLUE);
textView.setPadding(10,10,10,10);
textView.setText("Textview as Toast");
/** Create a Toast to display a View.
* Here we are going to display a TextView.
* Toast setView() is used to display a View.
* Toast Display Duration is Long. So it will display for long time.
* Toast setGravity() is used to set position to display the toast. */
Toast toastView = new Toast(this);
toastView.setView(textView);
toastView.setDuration(Toast.LENGTH_LONG);
toastView.setGravity(Gravity.CENTER, 0,0);
toastView.show();
}
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
public class MyBinder extends Binder
{
MyService getService()
{
return MyService.this;
}
}
}
请帮助我在哪里犯错误显示自定义吐司???
答案 0 :(得分:1)
有点迟,但有人可以发现它很有用:
你错过了:
<category android:name="android.intent.category.DEFAULT" />
所以你应该
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="MY_INTENT" />
</intent-filter>
答案 1 :(得分:0)
在manifest ::
中进行更改<service android:enabled="true" android:name="MyService"></service>
<receiver android:enabled="true" android:name="MyIntentReceiver">
到
<service android:enabled="true" android:name=".MyService"></service>
<receiver android:enabled="true" android:name=".MyIntentReceiver">
答案 2 :(得分:0)
您确定MyService已启动或创建的服务类??
当你想要启动服务时,你必须确保切换MyIntentReceiver, 有一种方法可以尝试: 您可以在Manifest.xml中设置以下代码
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE" />
</intent-filter>
</receiver>
运行你的应用;然后更改您的设备是飞行模式,您将找到您的服务已创建;
当然你可以用另一种方式来切换接收器;