我创建了一个使用检查朋友请求的服务。我想知道为什么“用户名”在logcat中重复出现以及如何解决它。我有一个悲伤的问题,就是谁知道如何通过数据到ThirdActivity的BroadcastReceiver ?? Log.d(“admin”,result)显示了朋友的名字但是为什么它不能在ThirdActivity中通知? (我在ThirdActivity中更新了一些内容并在登录前添加了logcat)
MyService.java
public int onStartCommand(Intent intent, int flags, int startId)
{
doSomethingRepeatedly();
return START_STICKY;
}
private void doSomethingRepeatedly(){
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
onClickLoad();
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.kryptoquest.com/tracker/checking.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username", s));
Log.d("Username",s);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
is = response.getEntity().getContent();
}catch(Exception e){
Log.e("log_tag", "Error:"+e.toString());
}
//convert response to string
try{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test",sb.toString());
is.close();
result = sb.toString();
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", result);
Log.d("admin",result);
sendBroadcast(intent);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
}
},10000,UPDATE_INTERVAL);
}
public void onClickLoad(){
try
{
FileInputStream fIn = openFileInput("user.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
while((charRead = isr.read(inputBuffer))>0)
{
String readString = String.copyValueOf(inputBuffer,0,charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
MainActivity.java
public void onCreate(Bundle savedInstanceState)
{
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{ ...
loading();
}
}
}
public void loading(){
dialog = ProgressDialog.show(this, "", "Please wait...", true);
new Thread(new Runnable() {
@Override
public void run()
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.kryptoquest.com/tracker/sql.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Username", name));
nameValuePairs.add(new BasicNameValuePair("Password", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0; //100
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
Log.d("MainActivity", buffer.toString());
if(buffer.charAt(0)=='Y')
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this, "login successfull", Toast.LENGTH_LONG).show();
finish();
onClickSave();
Intent abc = new Intent(MainActivity.this,ThirdActivity.class);
//Bundle b = new Bundle();
abc.putExtra("user", username.getText().toString());
//abc.putExtras(b);
startActivity(abc);
}
});
}
else
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
}
});
}
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
runOnUiThread(new Runnable() {
@Override
public void run()
{
dialog.dismiss();
}
});
}
}).start();
}
public void onClickSave(){
String str = username.getText().toString();
try
{
FileOutputStream fOut = openFileOutput("user.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "File saved successfully", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
ThirdActivity.java
public void onCreate(Bundle savedInstancesState){
super.onCreate(savedInstancesState);
setContentView(R.layout.list_screen);
user = getIntent().getExtras().getString("user");
Log.d("dg",user);
getList();
lv = (ListView) findViewById(android.R.id.list);
emptyText = (TextView)findViewById(android.R.id.empty);
intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
intentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
datapassed = intent.getStringExtra("DATAPASSED");
Log.d("datapassed",datapassed);
if(datapassed.length()>0){
data = datapassed.split("[*]");
dlength = data.length;
for(int i=0;i<dlength;i++){
if(i==dlength-1){
str += String.valueOf(data[i]);
}else{
str += String.valueOf(data[i]) + ",";
}
}
Log.d("dataServices",str);
displayNotification();
str = "";
}
/* else{
str = "abc";
displayNotification();
}*/
}
};
registerReceiver(intentReceiver, intentFilter);
}
protected void displayNotification(){
Intent i = new Intent(this,NotificationView.class);
i.putExtra("notification", notification);
i.putExtra("name",str);
Log.d("String",str);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mnotis =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notis = new Notification(R.drawable.notices2,"Reminder:You have " + dlength + " new friend request",System.currentTimeMillis());
notis.setLatestEventInfo(this,"Friend Request", str + "has sent you a friend request",pi);
notis.vibrate = new long[]{100,250,100,500};
mnotis.notify(0, notis);
}
checking.php
<?php
mysql_connect("localhost","xxx","xxx");
mysql_select_db("thomasl_GPSTracker");
$num = 1;
$name = $_POST['Username'];
$result = mysql_query("SELECT * FROM Friends WHERE responseRequest = '".$name."'") or die(mysql_error());
while( $row = mysql_fetch_array($result)) {
if($row['status']=="unapproved"&&$row['arrived']=="no"){
mysql_query("UPDATE Friends SET arrived='yes' WHERE sentRequest='".$row['sentRequest']."'");
if($num==1){
Print $row['sentRequest'];
$num++;
}else{
Print "*".$row['sentRequest'];
}
}
}
mysql_close();
?>
我使用解锁事件来呼叫服务。因此,当我解锁我的设备时,我可以获得我的朋友用户名,即EnEn,它应该被发送到ThirdActivity,它将通知用户得到朋友的请求。但问题是,sendBroadcast(意图)不起作用。它在这里停了下来。按下登录按钮并启动ThirdActivity之后,我收到了无限通知,显示“abc已向您发送了一个朋友请求”(我在ThirdActivity中修改了onReceive())。这意味着MyService的数据没有传递给ThirdAcitvity,当我登录时,MyService开始与ThirdAcitvity通信,但它没有通过。我怀疑这个问题可能是由于文件输入和输出导致的,用于保存用户的用户名和加载用户的用户名。 ** MainActivity是登录页面。
任何人都可以帮忙吗?提前谢谢。
logcat输出(登录前):
12-02 19:05:45.243: D/Username(21861): admin
12-02 19:05:45.323: I/global(21861): In close() at SocketHttpClientConnection
12-02 19:05:47.726: I/global(21861): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=48256], tmpsocket.getSoLinger()=-1
12-02 19:05:47.726: D/test(21861): EnEn
12-02 19:05:47.726: D/admin(21861): EnEn
12-02 19:06:00.238: D/Username(21861): adminadmin
12-02 19:06:00.258: I/global(21861): In close() at SocketHttpClientConnection
12-02 19:06:02.570: I/global(21861): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=56975], tmpsocket.getSoLinger()=-1
12-02 19:06:15.243: D/Username(21861): adminadminadmin
12-02 19:06:15.263: I/global(21861): In close() at SocketHttpClientConnection
12-02 19:06:16.264: I/global(21861): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=42588], tmpsocket.getSoLinger()=-1
12-02 19:06:30.237: D/Username(21861): adminadminadminadmin
12-02 19:06:30.257: I/global(21861): In close() at SocketHttpClientConnection
12-02 19:06:32.660: I/global(21861): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=53454], tmpsocket.getSoLinger()=-1
logcat输出(登录):
11-29 21:17:23.927: I/global(21100): In close() at SocketHttpClientConnection //unlock start
11-29 21:17:24.848: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=51701], tmpsocket.getSoLinger()=-1
11-29 21:17:24.858: D/test(21100): EnEn
11-29 21:17:24.858: D/admin(21100): EnEn
11-29 21:17:35.899: I/global(21100): In close() at SocketHttpClientConnection //unlock end
11-29 21:17:35.939: I/Adreno200-EGLSUB(21100): <ConfigWindowMatch:1991>: Format RGBA_8888. //start login(pressed login button)
11-29 21:17:36.750: D/MainActivity(21100): Y
11-29 21:17:36.770: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=60051], tmpsocket.getSoLinger()=-1
11-29 21:17:36.900: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x55038000 size:20766720 offset:20459520
11-29 21:17:36.900: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x56406000 size:21073920 offset:20766720
11-29 21:17:36.900: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x57820000 size:21381120 offset:21073920
11-29 21:17:37.130: D/dg(21100): admin
11-29 21:17:37.170: I/global(21100): In close() at SocketHttpClientConnection
11-29 21:17:37.260: I/Adreno200-EGLSUB(21100): <ConfigWindowMatch:1991>: Format RGBA_8888.
11-29 21:17:37.470: D/OpenGLRenderer(21100): Flushing caches (mode 0)
11-29 21:17:37.480: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x522e1000 size:23531520 offset:21995520
11-29 21:17:37.480: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x53b97000 size:4608000 offset:3072000
11-29 21:17:37.480: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x5468a000 size:6144000 offset:4608000
11-29 21:17:38.241: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=35677], tmpsocket.getSoLinger()=-1
11-29 21:17:38.241: D/test(21100): EnEn*EnEn*EnEn*
11-29 21:17:38.882: I/global(21100): In close() at SocketHttpClientConnection
11-29 21:17:39.973: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=44111], tmpsocket.getSoLinger()=-1
11-29 21:17:39.983: D/String(21100): abc
11-29 21:17:40.283: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x54e66000 size:20865024 offset:20766720
11-29 21:17:42.285: D/memalloc(21100): /dev/pmem: Unmapping buffer base:0x52306000 size:3194880 offset:3072000
11-29 21:17:53.876: I/global(21100): In close() at SocketHttpClientConnection
11-29 21:17:54.717: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=59125], tmpsocket.getSoLinger()=-1
11-29 21:17:54.717: D/String(21100): abc
11-29 21:18:08.881: I/global(21100): In close() at SocketHttpClientConnection
11-29 21:18:10.052: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=38139], tmpsocket.getSoLinger()=-1
11-29 21:18:10.052: D/String(21100): abc
11-29 21:18:23.876: I/global(21100): In close() at SocketHttpClientConnection
11-29 21:18:24.746: I/global(21100): call socket shutdown, tmpsocket=Socket[address=/96.127.151.252,port=80,localPort=37537], tmpsocket.getSoLinger()=-1
11-29 21:18:24.746: D/String(21100): abc
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.project"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:windowSoftInputMode="stateHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SMSReceiver">
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name=".Unapproved"
android:label="@string/title_activity_main"
android:launchMode="singleTask">
</activity>
<activity
android:name=".SecondActivity"
android:label="@string/title_activity_second" >
</activity>
<activity
android:name=".ThirdActivity"
android:label="@string/title_activity_third" >
</activity>
<activity
android:name=".AddFriend"
android:label="@string/title_activity_main" >
</activity>
<activity
android:name=".ServicesActivity"
android:label="Services" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NotificationView"
android:label="Details of notification" >
</activity>
<service android:name = ".MyService">
<intent-filter>
<action android:name="com.example.MyService" />
</intent-filter>
</service>
<receiver
android:name=".StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.USER_PRESENT"/>
</intent-filter>
</receiver>
<uses-library android:name="com.google.android.maps"/>
<activity
android:name=".Map"
android:label="Friend Location" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>